javascript - Jquery滚动以在页面加载时偏移目标div

标签 javascript jquery html css

我正在尝试滚动到 URL 中的 div。它可以是 21 个 ID 之一,例如:

url.com/test#lite1

url.com/test#lite2

url.com/test#lite3

我需要在页面加载时发生这种情况(用户来自电子书,应该看到他们点击的确切元素)。

这是我目前拥有的代码:

$(document).ready(function(){
    $('a[href^="#"]').load(function() {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top -150
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

</script>

它不起作用,我认为这是因为这部分(我不知道我在这里做什么):

$('a[href^="#"]').load(function() {

我还希望它位于页面的中心(而不是像浏览器滚动到 div 时那样在顶部被 chop )。请让我知道这是否正确:

$target.offset().top -150

提前致谢!

最佳答案

window.location.hash 包含 URL 中的当前哈希值,因此请使用它。由于哈希已经在 URL 中(正如您所说,他们通过单击带有哈希的链接来访问页面),因此您不需要手动添加它。 尝试使用这个:

$(document).ready(function(){
     $('html,body').animate({
          scrollTop: $(window.location.hash).offset().top-150
      }, 900, 'swing');
});

使用 wordpress,似乎 $ 需要用 jQuery 替换,所以它出来:

jQuery(document).ready(function(){
     jQuery('html,body').animate({
          scrollTop: jQuery(window.location.hash).offset().top-150
      }, 900, 'swing');
});

关于javascript - Jquery滚动以在页面加载时偏移目标div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33525293/

相关文章:

javascript - s3.getObject().createReadStream() : How to catch the error?

Jquery通过测试值获取单选按钮的id

javascript - 如何使div无限移动?

jquery - 调整 Html 表格单元格的大小效果

javascript - 选择下拉菜单时在移动 View 中放置内容

javascript - jQuery .on() 方法看不到新元素

javascript - 将数字转换为尽可能短的字符串,同时保持唯一性

javascript - div 中显示上一页,并显示最后一页数据表

html - 背景大小之间的差异 :cover and background-size:contain

javascript - 在 jQuery UI 中启用 Shift-Multiselect 可选择 div 元素