Javascript,检查元素是否已离开屏幕
Javascript, check if element has left the screen
我正在尝试测试<div>
是否已滚动出视图。
这就是我目前所拥有的,
$(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");
}
});
无论我在哪里滚动,都不会记录任何内容。
我试图测试的是div的底部是否已经超过了窗口的顶部。
这里有一个非常有用的Vanilla JS函数。
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
}
希望这能有所帮助!
divBottom
就是undefined
。您可以使用元素的top
偏移量,然后通过将其高度添加到顶部来计算其底部值,就像在这个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");
}
});
试试这个。
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
然后
if (myTop > windowTop && myTop < windowBottom) {
尝试:
$(window).scroll(function(){
//your code
});
相关文章:
- 如何将屏幕分辨率乘以 80%,然后在代码中使用
- 在不打开聊天屏幕的情况下制作Zopim-ding代理
- D3 - 如何确定元素何时离开屏幕
- Javascript,检查元素是否已离开屏幕
- 当光标离开屏幕时,游戏不会't以Javascript结尾
- CSS包含+的位置部分离开屏幕
- 检测下拉导航是否会离开屏幕并重新定位
- VueJS & Laravel,在用户离开屏幕时发出后请求
- 我不希望我的“播放器”离开屏幕,我该如何防止这种情况
- 让用户通过网站离开他的屏幕保护程序
- jQuery或JS,使元素离开屏幕底部并在顶部输入
- 图像旋转到宽离开我的屏幕如何保持静态或缩短宽度
- 如何将光标设置为离开屏幕
- 当手指离开屏幕上的对象时进行检测
- 检查元素是否离开屏幕的右边缘
- jQuery -如何监听鼠标离开屏幕的区域
- 隐藏列表元素,如果他们离开屏幕
- 如何创建一个永远不会离开屏幕的html工具提示
- 如何知道元素何时会离开屏幕
- 当jquery-ui-draggable的父项在排序过程中隐藏在屏幕之外时,光标会离开该排序项