首页 > 当滚动条滚动到某元素时触发函数

当滚动条滚动到某元素时触发函数

<div style="height:1000px;">11111</div>
<div id="showIt">22222</div>

如何当滚动条滚动到 showIt 元素的时候触发函数?
主要不知道怎么计算。

可以给个思路吗?谢谢。


用jQuery 的话可以查查position,offset这两个API用法,用别的东西,那就实现这两个API。


<!DOCTYPE html>
<html>
<head>
<style type="text/css">

#showIt{width: 200px;height: 200px;background-color: red;position: absolute;top: 1500px;}

</style>
</head>
<body style="height:2000px;">
<div id="showIt"></div>
</body>
<script type="text/javascript">

document.onscroll=function()
{
    var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
    var cHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;
    var oDiv=document.getElementById('showIt');
    if(scrollTop>(oDiv.offsetTop-cHeight))
    alert('触发了')
}

</script>
</html>

先上答案。
废话不多说,解释下逻辑。
当你滚动窗口的时候,只有你的scrollTop是变化的,当你滚动的越来越多到了一定程度,那就能看到你的DIV了。
知道这个道理后就很简单了。
其实就是只要你的滚动距离大于DIV当前的TOP减去视窗大小,你就能看到这个DIV了。
所以条件按照这个写就可以。了

【热门文章】
【热门文章】