jQuery滚动到页面加载时偏移目标div [英] Jquery scroll to offset target div on page load

查看:80
本文介绍了jQuery滚动到页面加载时偏移目标div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to scroll to the div that is in the URL. It could be one of 21 IDs like:

url.com/test#lite1

url.com/test#lite1

url.com/test#lite2

url.com/test#lite2

url.com/test#lite3

url.com/test#lite3

我需要在页面加载时发生这种情况(用户来自一本电子书,应该看到他们单击的确切项目).

I need this to happen on page load (user is coming from an ebook and should see the exact item they clicked on).

这是我当前拥有的代码:

Here is the code I currently have:

$(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>

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

It doesn't work and I think it's because of this part (I have no idea what I'm doing here):

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

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

I also want it to be in the center of the page (not at the top cut off like browsers do when scrolling to divs). Please let me know if this is correct:

$target.offset().top -150

非常感谢!

推荐答案

window.location.hash在URL中包含当前哈希,因此可以使用它.由于哈希已经存在于URL中(正如您所说的那样,它们通过单击带有哈希的链接而进入页面),因此您无需手动添加它. 尝试使用此:

window.location.hash contains the current hash in the URL so use that. As the hash is already in the URL(as you said that they come to page by clicking on link with hash) so you don't need to add it manually. Try using this :

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

使用wordpress,似乎$需要用jQuery代替,这样就可以得出:

Using wordpress, it seems the $ needs to be replaced by jQuery so it comes out to:

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

这篇关于jQuery滚动到页面加载时偏移目标div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆