How to find scroll top value for div

醉酒当歌 提交于 2019-12-10 18:24:09

问题


I am working on responsive site. We need when a user see video section that's need to autoplay. If set scroll top for video tag is not working. But i set scrolltop to window it's working fine.

<video id="test">
</video>

<script>
$(document).ready(function () {
   $(window).scroll(function () {
      var js=$('#test-28').scrollTop();
        console.log(js);
      });
   });
</script>

Its always show 0

Anyone know how to slove this


回答1:


You need use offest().top to get distance to reach video element. scrollTop will get window scroll distance not distance to an element. Just use this:

$('#test').offset().top

jsFiddle

   $(window).scroll(function () {
      var scrollTop = $(window).scrollTop();
       var scrollToVid = $('#test').offset().top
        console.log(scrollTop);
        console.log(scrollToVid);

        if ($(window).scrollTop() >= scrollToVid) {
        alert('You reached to the video!');
        }
      });



回答2:


You can also use

document.body.scrollTop + Element.getBoundingClientRect().top

  1. document.body.scrollTop is the offset of document had scrolled out viewport
  2. Element.getBoundingClientRect().top is the offset of element to viewport top.


来源:https://stackoverflow.com/questions/36029058/how-to-find-scroll-top-value-for-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!