滚动到Chrome中的页面加载元素

时间:2017-09-23 02:59:07

标签: jquery hash scroll pageload

是否可以滚动到Chrome中页面加载时从url hash获取id的元素?我用Google搜索并尝试了所有内容,但Chrome似乎没有任何效果。例如,以下代码适用于Safari,但在Chrome中无效:

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

4 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

下面:

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

我们正在设置scrollTop方法的动画,并且在这里:

$(element).offset().top

我们正在从页面顶部偏移元素。

答案 1 :(得分: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>

答案 2 :(得分:0)

Chrome会在页面加载前尝试滚动,因此我在窗口加载函数中使用超时功能解决了问题。不确定它是否是最佳解决方案,但它确实有效。

setTimeout(function(){
  $("html, body").animate({
     scrollTop: $(target).offset().top}, 300);
}, 1000);

答案 3 :(得分:0)

Chrome中的问题是,DOMContentLoadeddocument.readyState时会触发interactive,但目前尚无法进行程序化滚动。在超时MIGHT起作用的时候,取决于它的持续时间和页面加载的速度,这是万无一失的解决方案:

  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,就调用回调函数。