宝哥软件园

确定指定的dom元素是否在屏幕上的JS方法示例

编辑:宝哥软件园 来源:互联网 时间:2021-09-06

刷网页的时候,有时候会遇到这样的情况。当dom元素滚动到可见区域时,会显示动画,非常有趣。那么这是如何实现的呢?

实施原则

要实现这个功能,需要知道具体的实现原理。我们开门见山吧。

当通过浏览器浏览网页时,我们看起来像这样,如图所示

页面的长度和宽度,以及每个dom的坐标都是静态的,只有显示窗口的坐标是移动的。考虑到这一点,判断dom元素是否可见是非常简单的。

我们需要知道三个坐标才能知道当前dom是否在可见区域,即

显示窗口顶部坐标dom元素底部坐标判断规则是当dom元素中心坐标的X、Y坐标小于显示窗口顶部,大于显示窗口底部坐标时,可以判断坐标在可见区域。

好的,那么下一步就是知道如何计算这三个坐标了。

第一个是窗口的顶部坐标,即页面滚动条的滚动距离。

接下来是底部坐标,它是滚动条的距离加上当前可视窗口的高度。

最后,dom元素的中心距离是从dom元素顶部开始的高度加上它自己的高度。

原理就是这么简单。

具体实现

明白了原理,具体实现就很简单了。下面直接粘贴一个简单的dom代码来做下面的例子,在实际生产中需要进行优化,比如第一次屏幕显示,这里就不赘述了。

!DOCTYPE html html lang=' en ' head meta charset=' UTF-8 ' title document/title/head style type=' text/CSS '。box { width : 100%;高度: 200 px;背景# ff0000边距-bottom : 10px;文本对齐:中心;color: # fff线高: 200 px;font-family:微软雅黑;font-size : 40px;} .动画{ animation: showText 1s} @关键帧ShowText { from { font-size : 20px;}到{ font-size : 40px;} }/stylebodydiv class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div div class=' box '/div/body script type=' text/jav文件。addeventlistener ('scroll ',function(){//滚动条高度Window height=可见区域底部高度var可见底部=window。scrolly document . document element . client height;//可见区域的顶部高度var visibleTop=window.scrollYfor(var I=0;一、方框.长度;i ) { var centerY=box[i]。offsetTop(方框[i])。offset ThEight/2);if(centerivvisibletopcenterivvisiblebottom){ box[I]。innerhtml='区域可见'框[I]。setattribute ('class ',' boxanimate') console.log('第' I '个区域可见');}else{ box[i]。innerHTML=方框[一]。setattribute ('class ',' box') console.log('第' I '个区域不可见');} } })/脚本/html渲染

摘要

以上就是本文的全部内容。希望这篇文章的内容对你的学习或工作有所帮助。有问题可以留言交流。

更多资讯
游戏推荐
更多+