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

查看:89
本文介绍了javascript - 当滚动条滚动到某元素时触发函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

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

可以给个思路吗?谢谢。

解决方案

<!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了。
所以条件按照这个写就可以。了

这篇关于javascript - 当滚动条滚动到某元素时触发函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆