问题
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
document.body.scrollTop
is the offset of document had scrolled out viewportElement.getBoundingClientRect().top
is the offset of element to viewport top.
来源:https://stackoverflow.com/questions/36029058/how-to-find-scroll-top-value-for-div