jQuery延迟滚动到#ID

时间:2018-11-09 18:51:23

标签: javascript jquery html scroll

我想在一段时间后将Scroll应用于div。该代码可以很好地工作,因为它可以延迟滚动,但是我不知道如何将其应用于特定的DIV ID。

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

1 个答案:

答案 0 :(得分:1)

您可以使用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>

相关问题