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

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

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

可以给个思路吗?谢谢。


动漫人物
浏览 983回答 1
1回答

一只甜甜圈

<!DOCTYPE html><html><head><style type="text/css">#showIt{width:&nbsp;200px;height:&nbsp;200px;background-color:&nbsp;red;position:&nbsp;absolute;top:&nbsp;1500px;}</style></head><body style="height:2000px;"><div id="showIt"></div></body><script type="text/javascript">document.onscroll=function(){&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;scrollTop=document.documentElement.scrollTop||document.body.scrollTop;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;cHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;oDiv=document.getElementById('showIt');&nbsp;&nbsp;&nbsp;&nbsp;if(scrollTop>(oDiv.offsetTop-cHeight)) &nbsp;&nbsp;&nbsp;&nbsp;alert('触发了') }</script></html>先上答案。废话不多说,解释下逻辑。当你滚动窗口的时候,只有你的scrollTop是变化的,当你滚动的越来越多到了一定程度,那就能看到你的DIV了。知道这个道理后就很简单了。其实就是只要你的滚动距离大于DIV当前的TOP减去视窗大小,你就能看到这个DIV了。所以条件按照这个写就可以。了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript