当DIV在视图中时触发Javascript事件 [英] Fire Javascript Event When a DIV is in View
问题描述
当某个DIV进入页面查看时,是否可以触发特定的javascript事件?
Is it possible to fire a specific javascript event when a certain DIV comes into view on the page?
比方说,我有一个非常大的页面,比如2500x2500,我有一个位于1980x1250位置的40x40 div。 div不一定是手动定位的,它可能存在,因为内容将其推到那里。现在,当用户滚动到div可见的点时,是否可以运行一个函数?
Say, for example, I have a very large page, like 2500x2500 and I have a 40x40 div that sits at position 1980x1250. The div is not necessarily manually positioned, it could be there due to the content pushing it there. Now, is it possible to run a function when the user scrolls to a point where the div becomes visible?
推荐答案
不自动。你必须通过比较div矩形与可见页面矩形的坐标来捕捉滚动事件并检查它是否在视图中。
Not automatically. You would have to catch scroll events and check for it being in view each time by comparing the co-ordinates of the div rectangle with the visible page rectangle.
这是一个最小的例如。
<div id="importantdiv">hello</div>
<script type="text/javascript">
function VisibilityMonitor(element, showfn, hidefn) {
var isshown= false;
function check() {
if (rectsIntersect(getPageRect(), getElementRect(element)) !== isshown) {
isshown= !isshown;
isshown? showfn() : hidefn();
}
};
window.onscroll=window.onresize= check;
check();
}
function getPageRect() {
var isquirks= document.compatMode!=='BackCompat';
var page= isquirks? document.documentElement : document.body;
var x= page.scrollLeft;
var y= page.scrollTop;
var w= 'innerWidth' in window? window.innerWidth : page.clientWidth;
var h= 'innerHeight' in window? window.innerHeight : page.clientHeight;
return [x, y, x+w, y+h];
}
function getElementRect(element) {
var x= 0, y= 0;
var w= element.offsetWidth, h= element.offsetHeight;
while (element.offsetParent!==null) {
x+= element.offsetLeft;
y+= element.offsetTop;
element= element.offsetParent;
}
return [x, y, x+w, y+h];
}
function rectsIntersect(a, b) {
return a[0]<b[2] && a[2]>b[0] && a[1]<b[3] && a[3]>b[1];
}
VisibilityMonitor(
document.getElementById('importantdiv'),
function() {
alert('div in view!');
},
function() {
alert('div gone away!');
}
);
</script>
您可以通过以下方式改善:
You could improve this by:
- 使所有祖先
溢出
滚动
或onscroll
自动
并调整其左上角的滚动位置 - 检测
溢出
滚动
,自动
和隐藏
使用addEventListener
/attachEvent $ c裁剪将div放在屏幕外
- $ c>允许多个VisibilityMonitors和其他东西使用调整大小/滚动事件
- 一些兼容性攻击
getElementRect
来使用在某些情况下,ords更准确,有些事件解除绑定以避免IE6-7内存泄漏,如果你真的需要。
- making it catch
onscroll
on all ancestors that haveoverflow
scroll
orauto
and adjusting the top/left co-ords for their scroll positions - detecting
overflow
scroll
,auto
andhidden
cropping putting the div off-screen - using
addEventListener
/attachEvent
to allow multiple VisibilityMonitors and other things using the resize/scroll events - some compatibility hacks to
getElementRect
to make the co-ords more accurate in some cases, and some event unbinding to avoid IE6-7 memory leaks, if you really need to.
这篇关于当DIV在视图中时触发Javascript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!