在Chrome中页面加载时滚动到元素

3

在Chrome浏览器中,是否有可能在页面加载时通过URL哈希标识符滚动到指定ID的元素?我已经搜索并尝试了各种方法,但是在Chrome中似乎没有任何方法能够实现。例如,以下代码可以在Safari中工作,但在Chrome中则无法实现:

$(window).load(function() {
  if(location.hash) {
    var target = location.hash;
    location.hash = '';
    $('html,body').animate({scrollTop: $(target).offset().top + 'px'}, 300);
  }
});

尝试使用 $(window) 替代 $('html,body') - Dan D
Chrome 响应 $(document).ready(function () {})... - Praveen Kumar Purushothaman
尝试过使用$(window)代替$('html,body')以及$(document).ready(function () {}),但在Chrome中都无法正常工作,甚至会破坏Safari。 - iamfredrik
移除 + 'px'。scrollTop 函数需要一个数字。 - Jacob
4个回答

1
在Chrome中的问题是,当document.readyStateinteractive时,DOMContentLoaded被触发,但此时还不能进行程序化滚动。虽然超时可能有效,取决于超时时间和页面加载速度,但这是一种可靠的解决方案:
  let callback = () => {
        if (document.readyState === 'complete') {
              $(selector).animate({
                    scrollTop: value
              }, time);
        }
  };

  if (document.readyState === 'complete') {
        callback();
  } else {
        document.addEventListener('readystatechange', callback);
  }

在这个片段中,readyState立即被检查,如果它已经是complete,回调函数将立即被调用,否则,我们添加一个事件侦听器到readystatechange事件,并在readyStatecomplete时调用回调函数。

0

首先,您必须使用window.location.hash而不是仅使用location.hash。这里是工作示例,我已在Chrome中进行了测试(示例中没有window.location.hash,只有滚动):

$(window).load(function() {
    $('html, body').animate({
        scrollTop: $("#elementToScroll").offset().top
    }, 2000);
});
.regular {
  width: 100%;
  height: 500px;
  background-color: blue;
  border: 5px black solid;
  margin: 16px;
}

#elementToScroll {
  width: 100%;
  height: 500px;
  background-color: yellow;
  border: 5px black solid;
  margin: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regular"></div>
<div class="regular"></div>
<div class="regular"></div>
<div id="elementToScroll"></div>

这里:

$(selector).animate({
    scrollTop: value
}, time);

我们正在使用scrollTop方法进行动画,代码如下:

$(element).offset().top

我们正在获取元素相对于页面顶部的偏移量。


@iamfredrik,我给你了基本的问题理解,但是你需要根据自己的需求进行适应。 - P.S.
我不明白你的示例与我最初提供的示例有何不同。在脚本中定义目标元素时,它确实执行相同的操作。问题在于,当从URL中获取目标元素时,使用var target = location.hash; 它无法正常工作。 - iamfredrik
@iamfredrik,如果问题在于获取位置哈希,则应该是window.location.hash,而不仅仅是location.hash - P.S.
1
无论哪种方式都应该可以工作 https://www.w3schools.com/jsref/prop_loc_hash.asp - iamfredrik
看起来 Chrome 太快了。它在页面完全加载之前尝试滚动到元素,因此最终停留在顶部。有没有什么办法解决这个问题? - iamfredrik
显示剩余5条评论

0

试着运行这个 :)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").scroll(function(){
       location.hash = "part5";
       alert(location.hash)
    });
});
</script>
</head>
<body>

<p>Try the scrollbar in the div</p>

<div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>

<p>Scrolled <span>0</span> times.</p>

</body>
</html>

不好意思,我不知道如何在普通的JavaScript中实现它。你能提供一个可行的例子吗? - iamfredrik
我刚刚在JQuery中更新了我的答案,这样你就可以玩弄代码并得到你所需的内容 :) - emjr
我不认为这个例子能解决问题。.scroll()函数不会滚动,而是对用户的滚动做出反应。我正在寻找一种使用.scrollTop()自动滚动页面到URL提供的哈希值的解决方案。 - iamfredrik

0
Chrome 会在页面加载完成前尝试滚动,因此我在窗口加载函数内使用超时函数解决了这个问题。不确定这是否是最佳解决方案,但它能够奏效。
setTimeout(function(){
  $("html, body").animate({
     scrollTop: $(target).offset().top}, 300);
}, 1000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接