jquery - 如何在加载页面时禁用 anchor 跳转

标签 jquery scroll hashtag

当我访问 my_site.com/page.php#something 时,滚动位置是携带此特定主题标签的元素之一,而不是页面顶部。

执行 window.scrollTo(0, 0); 不会改变这一事实。那还能做什么呢?

编辑:还尝试了 How to disable anchor "jump" when loading a page? 接受的答案。似乎不再起作用了。

最佳答案

您要做的就是存储主题标签以供以后使用,然后将其删除,以便浏览器没有任何内容可滚动。

重要的是,不要将这部分代码放入 $() 或 $(window).load() 函数中,因为这会太晚,并且浏览器已经移至该标记。

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).load(function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

关于jquery - 如何在加载页面时禁用 anchor 跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096621/

相关文章:

jquery - 滑动切换不适用于向上滑动

javascript - jQuery scrollTop() 在滚动方向改变时返回错误的偏移量

javascript - 模态不起作用

javascript - IE Javascript 错误 "Object doesn' t 支持此属性或方法"within jQuery

html - 表格无法在 IOS 设备上滚动?

javascript - 获取动态元素的顶部位置,不涉及任何事件

javascript - 在 rails 中将主题标签转换为适当的链接

php - 从 PHP 中的字符串中提取 Twitter 标签

python - 标签 python html

jQuery Datatables 旧版加载动画