admin管理员组文章数量:1320588
I'm trying to test if a <div>
has been scrolled out of view.
This is what I have so far,
$(window).on('scroll',function(){
var divBottom = $('#home').offset().bottom;
var windowTop = $(window).scrollTop();
var windowBottom = windowTop + $(window).height();
if (divBottom >= windowTop) {
console.log("yes");
} else {
console.log("no");
}
});
No matter where I scroll, nothing is logged.
What I was trying to test is if the bottom of the div has gone past the top of the window.
I'm trying to test if a <div>
has been scrolled out of view.
This is what I have so far,
$(window).on('scroll',function(){
var divBottom = $('#home').offset().bottom;
var windowTop = $(window).scrollTop();
var windowBottom = windowTop + $(window).height();
if (divBottom >= windowTop) {
console.log("yes");
} else {
console.log("no");
}
});
No matter where I scroll, nothing is logged.
What I was trying to test is if the bottom of the div has gone past the top of the window.
Share Improve this question edited Dec 17, 2013 at 12:55 user2672373 asked Dec 17, 2013 at 12:48 user2979139user2979139 1612 silver badges12 bronze badges 1- 1 this can help you stackoverflow./questions/487073/… – MaVRoSCy Commented Dec 17, 2013 at 12:52
4 Answers
Reset to default 6There's a very useful Vanilla JS function that could help here.
var divposition = document.getElementById('home').getBoundingClientRect();
if( divposition.left+divposition.width < 0) {
// element is off to the left of the view
}
if( divposition.top+divposition.height < 0) {
// element is off the top of the view
}
if( divposition.top > window.innerHeight) {
// element is off the bottom of the view
}
if( divposition.left > window.innerWidth) {
// element is off to the right of the view
}
Hope this helps!
divBottom
is undefined
. You can use the top
offset of the element and then calculate it's bottom value by adding it's height to the top, like in this fiddle.
$(window).on('scroll',function(){
var $home = $('#home');
var divBottom = $home.offset().top + $home.height();
var windowTop = $(window).scrollTop();
console.log(divBottom, windowTop);
if (divBottom >= windowTop) {
console.log("yes");
} else {
console.log("no");
}
});
Try this.
var myTop = $('#home').offset().top; // the top y location of your element
var windowTop = $(window).scrollTop(); // the top of the window
var windowBottom = windowTop + $(window).height(); // the bottom of the window
then
if (myTop > windowTop && myTop < windowBottom) {
Try:
$(window).scroll(function(){
//your code
});
本文标签: jQueryJavascriptcheck if element has left the screenStack Overflow
版权声明:本文标题:jquery - Javascript, check if element has left the screen - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742086507a2420011.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论