Open huihuiha opened 3 years ago
IntersectionObserver这个例子感觉不对呢,一上来所有的div就全都是黄色的了
@dlutwangyu callback 改成这样试试
function getYellow(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting){
$(entry.target).css("background-color", "yellow");
observer.unobserve(entry.target)
}
});
}
IntersectionObserver这个例子感觉不对呢,一上来所有的div就全都是黄色的了
一、用途
可视区域即我们浏览网页的设备肉眼可见的区域,如下图
在日常开发中,我们经常需要判断目标元素是否在视窗之内或者和视窗的距离小于一个值(例如 100 px),从而实现一些常用的功能,例如:
二、实现方式
判断一个元素是否在可视区域,我们常用的有三种办法:
offsetTop、scrollTop
getBoundingClientRect
Intersection Observer
offsetTop、scrollTop
offsetTop
,元素的上外边框至包含元素的上内边框之间的像素距离,其他offset
属性如下图所示:下面再来了解下
clientWidth
、clientHeight
:clientWidth
:元素内容区宽度加上左右内边距宽度,即clientWidth = content + padding
clientHeight
:元素内容区高度加上上下内边距高度,即clientHeight = content + padding
这里可以看到
client
元素都不包括外边距最后,关于
scroll
系列的属性如下:scrollWidth
和scrollHeight
主要用于确定元素内容的实际大小scrollLeft
和scrollTop
属性既可以确定元素当前滚动的状态,也可以设置元素的滚动位置scrollTop > 0
scrollLeft > 0
将元素的
scrollLeft
和scrollTop
设置为 0,可以重置元素的滚动位置注意
下面再看看如何实现判断:
公式如下:
代码实现:
getBoundingClientRect
返回值是一个
DOMRect
对象,拥有left
,top
,right
,bottom
,x
,y
,width
, 和height
属性属性对应的关系图如下所示:
当页面发生滚动的时候,
top
与left
属性值都会随之改变如果一个元素在视窗之内的话,那么它一定满足下面四个条件:
实现代码如下:
Intersection Observer
Intersection Observer
即重叠观察者,从这个命名就可以看出它用于判断两个元素是否重叠,因为不用进行事件的监听,性能方面相比getBoundingClientRect
会好很多使用步骤主要分为两步:创建观察者和传入被观察者
创建观察者
通过
new IntersectionObserver
创建了观察者observer
,传入的参数callback
在重叠比例超过threshold
时会被执行`关于
callback
回调函数常用属性如下:传入被观察者
通过
observer.observe(target)
这一行代码即可简单的注册被观察者三、案例分析
实现:创建了一个十万个节点的长列表,当节点滚入到视窗中时,背景就会从红色变为黄色
Html
结构如下:css
样式如下:往
container
插入1000个元素这里,首先使用
getBoundingClientRect
方法进行判断元素是否在可视区域然后开始监听
scroll
事件,判断页面上哪些元素在可视区域中,如果在可视区域中则将背景颜色设置为yellow
通过上述方式,可以看到可视区域颜色会变成黄色了,但是可以明显看到有卡顿的现象,原因在于我们绑定了
scroll
事件,scroll
事件伴随了大量的计算,会造成资源方面的浪费下面通过
Intersection Observer
的形式同样实现相同的功能首先创建一个观察者
getYellow
回调函数实现对背景颜色改变,如下:最后传入观察者,即
.target
元素可以看到功能同样完成,并且页面不会出现卡顿的情况
参考文献