You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现账户页787px以下视口自动滚动到#hello锚点

实现方案

以下为无依赖的原生JS实现,逻辑轻量,完全匹配你的需求:

基础版(仅页面加载时触发,推荐)

仅需将以下代码添加到账户页的脚本中即可,全局引入也不会在其他页面生效:

document.addEventListener('DOMContentLoaded', () => {
  // 按需修改账户页判断规则,以下二选一即可
  // 规则1:通过URL路径判断,示例为路径包含/account时判定为账户页
  const isAccountPage = window.location.pathname.includes('/account');
  // 规则2:通过页面独有标识判断,示例为body带page-account类时判定为账户页
  // const isAccountPage = document.body.classList.contains('page-account');

  // 同时满足账户页、视口宽度≤787px两个条件才执行滚动
  if (isAccountPage && window.innerWidth <= 787) {
    const target = document.querySelector('#hello');
    target && target.scrollIntoView({
      behavior: 'smooth', // 不需要平滑滚动可删除这一行
      block: 'start'
    });
  }
});

配置说明

  • 不需要平滑滚动效果直接删除behavior: 'smooth'配置项,即可实现瞬间跳转
  • 账户页判断规则可根据实际业务场景调整,比如匹配URL参数、页面独有元素都可以
  • 注意:如果是单页应用(SPA),需要把逻辑放到账户页组件的挂载生命周期钩子中执行

增强版(支持窗口缩放触发)

如果需要适配用户手动调整窗口大小的场景(比如PC端用户把窗口从大屏拉窄到787px以下),可以使用带防抖的增强版本:

document.addEventListener('DOMContentLoaded', () => {
  // 账户页判断规则,和基础版一致,按需修改
  const isAccountPage = window.location.pathname.includes('/account');
  if (!isAccountPage) return;

  // 防抖逻辑,避免窗口缩放时频繁触发执行
  let timer = null;
  const handleCheckScroll = () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      if (window.innerWidth <= 787) {
        document.querySelector('#hello')?.scrollIntoView({ behavior: 'smooth' });
      }
    }, 100);
  };

  // 页面加载时执行一次
  handleCheckScroll();
  // 监听窗口大小变化
  window.addEventListener('resize', handleCheckScroll);
});

内容的提问来源于stack exchange,提问作者neosan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:39:05