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

如何从其他页面跳转至首页并滚动到指定ID元素?

实现跨页面跳转并平滑滚动到指定元素

要完成跨页面跳转至首页并平滑滚动到#home-features元素的需求,需要从三个部分调整代码:

1. 配置菜单链接的跳转目标

先确保你的.about-us-scrolling菜单元素的href指向带锚点的首页地址:

<a href="mywebsite.com#home-features" class="about-us-scrolling">关于我们</a>

2. 优化点击事件逻辑(兼容页面内和跨页面场景)

更新原有jQuery代码,判断当前页面是否为首页,分别处理两种场景:

jQuery(".about-us-scrolling").click(function(e) {
    // 根据实际域名和首页路径调整判断条件
    const isHomePage = window.location.host === 'mywebsite.com' && window.location.pathname === '/';
    
    if (isHomePage) {
        e.preventDefault(); // 阻止默认跳转,执行页面内平滑滚动
        jQuery('html, body').animate({
            scrollTop: jQuery("#home-features").offset().top
        }, 2000);
    }
    // 非首页场景下,不阻止默认行为,让浏览器跳转到带锚点的首页
});

3. 首页加载时处理锚点平滑滚动

在首页的JS中添加页面加载完成后的逻辑,替换浏览器默认的锚点跳转为平滑滚动:

jQuery(document).ready(function() {
    // 等待所有页面资源加载完成,确保元素位置计算准确
    jQuery(window).on('load', function() {
        const targetAnchor = window.location.hash;
        if (targetAnchor === '#home-features' && jQuery(targetAnchor).length) {
            // 重置默认锚点跳转的位置
            window.scrollTo(0, 0);
            // 执行平滑滚动到目标元素
            jQuery('html, body').animate({
                scrollTop: jQuery(targetAnchor).offset().top
            }, 2000);
        }
    });
});

注意事项

  • 如果首页的路径不是根路径(比如mywebsite.com/index.html),需要修改isHomePage判断中的pathname值。
  • 使用window.load而非仅document.ready,是为了确保图片、视频等资源加载完成后再计算元素位置,避免滚动位置偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:30:29