<!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('觸發(fā)了')
}</script>
</html>
先上答案。
廢話不多說,解釋下邏輯。
當(dāng)你滾動窗口的時候,只有你的scrollTop是變化的,當(dāng)你滾動的越來越多到了一定程度,那就能看到你的DIV了。
知道這個道理后就很簡單了。
其實(shí)就是只要你的滾動距離大于DIV當(dāng)前的TOP減去視窗大小,你就能看到這個DIV了。
所以條件按照這個寫就可以。了