首页 > 解决方案 > Jquery延迟滚动到#ID

问题描述

我正在尝试在一段时间后将 Scroll 应用于 div。此代码运行良好,因为它会延迟滚动,但我不知道如何将其应用于特定的 DIV ID。

 $(document).ready(function(){
setTimeout(function (){var scroll= $(window).scrollTop();
scroll= scroll+ 800; 
$('html, body').animate({scrollTop: scroll}, 5000);}, 5000);
});

标签: javascriptjqueryhtmlscroll

解决方案


您可以使用该offset()方法获取文档中元素的位置topleft位置。

$(document).ready(function() {
  setTimeout(function() {
    //get the offset of the target in the page
    var scroll = $('#target').offset().top;
    
    $('html, body').animate({
      scrollTop: scroll
    }, 2000);
  }, 2000);
});
#target {
  background-color: red;
  width: 400px;
  min-height: 1400px;
  margin-top: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>


推荐阅读