// 用构造函数生成观察者实例
let observer = new IntersectionObserver((entries, observer) => {
// 回调函数中可以拿到每次相交发生时所产生的交集的信息
for (let entry of entries) {
console.log(entry.time)
console.log(entry.target)
console.log(entry.rootBounds)
console.log(entry.boundingClientRect
console.log(entry.intersectionRect)
console.log(entry.intersectionRatio)
}
}, { // 构造函数的选项
root: null,
threshold: [0, 0.5, 1],
rootMargin: "50px, 0px"
})
// 实例属性
observer.root
observer.rootMargin
observer.thresholds
// 实例方法
observer.observe()
observer.unobserve()
observer.disconnect()
observer.takeRecords()
new IntersectionObserver(callback, options)
<div id="info">我藏在页面底部,请向下滚动</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: calc(100vh + 500px);
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
if (!target.isIntersecting) {
info.textContent = "我出来了"
target.isIntersecting = true
} else {
info.textContent = "我藏在页面底部,请向下滚动"
target.isIntersecting = false
}
}, {
root: null // null 的时候可以省略
})
observer.observe(target)
</script>
<div id="root">
<div id="info">向下滚动就能看到我</div>
<div id="target"></div>
</div>
<style>
#root {
position: relative;
width: 200px;
height: 100vh;
margin: 0 auto;
overflow: scroll;
border: 1px solid #ccc;
}
#info {
position: fixed;
}
#target {
position: absolute;
top: calc(100vh + 500px);
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
if (!target.isIntersecting) {
info.textContent = "我出来了"
target.isIntersecting = true
} else {
info.textContent = "向下滚动就能看到我"
target.isIntersecting = false
}
}, {
root: root
})
observer.observe(target)
</script>
<div id="root">
<div id="info">慢慢向下滚动</div>
<div id="target"></div>
</div>
<style>
#root {
position: relative;
width: 200px;
height: calc(100vh + 500px);
margin: 0 auto;
overflow: scroll;
border: 1px solid #ccc;
}
#info {
position: fixed;
}
#target {
position: absolute;
top: calc(100vh + 1000px);
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
if (!target.isIntersecting) {
info.textContent = "我和 root 相交了,但你还是看不见"
target.isIntersecting = true
} else {
info.textContent = "慢慢向下滚动"
target.isIntersecting = false
}
}, {
root: root
})
observer.observe(target)
</script>
<div id="info">
慢慢向下滚动,相交次数:
<span id="times">0</span>
</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: 200%;
width: 100px;
height: 100px;
background: red;
margin-bottom: 100px;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
times.textContent = +times.textContent + 1
}, {
threshold: [0, 0.5, 1]
})
observer.observe(target)
</script>
<script>
new IntersectionObserver(() => {}, {
threshold: 2 // SyntaxError: Failed to construct 'Intersection': Threshold values must be between 0 and 1.
})
</script>
<div id="info">图片在页面底部,仍未加载,请向下滚动</div>
<img id="img" src="data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA="
data-src="https://img.alicdn.com/bao/uploaded/i7/TB1BUK4MpXXXXa1XpXXYXGcGpXX_M2.SS2">
<style>
#info {
position: fixed;
}
#img {
position: absolute;
top: 300%;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
observer.unobserve(img)
info.textContent = "开始加载图片!"
img.src = img.dataset.src
}, {
rootMargin: "500px 0px"
})
observer.observe(img)
</script>
<script>
new IntersectionObserver(() => {}, {
rootMargin: "10em" // SyntaxError: Failed to construct 'Intersection': rootMargin must be specified in pixels or percent.
})
</script>
new IntersectionObserver(() => {}).root // null
new IntersectionObserver(() => {}, {root: document.body}).root // document.body
new IntersectionObserver(() => {}).rootMargin // "0px 0px 0px 0px"
new IntersectionObserver(() => {}, {rootMargin: "50px"}).rootMargin // "50px 50px 50px 50px"
new IntersectionObserver(() => {}, {rootMargin: "50% 0px"}).rootMargin // "50% 0px 50% 0px"
new IntersectionObserver(() => {}, {rootMargin: "50% 0px 50px"}).rootMargin // 50% 0px 50px 0px"
new IntersectionObserver(() => {}, {rootMargin: "1px 2px 3px 4px"}).rootMargin // "1px 2px 3px 4px"
new IntersectionObserver(() => {}).thresholds // [0]
new IntersectionObserver(() => {}, {threshold: 1}).thresholds // [1]
new IntersectionObserver(() => {}, {threshold: [0.3, 0.6]}).thresholds // [[0.30000001192092896, 0.6000000238418579]]
Object.isFrozen(new IntersectionObserver(() => {}).thresholds) // true, 是个被 freeze 过的数组
requestIdleCallback(() => {
if (entries.length > 0) {
callback(entries, observer)
}
}, {
timeout: 100
})
<script>
setInterval(() => {
let observer = new IntersectionObserver(entries => {
if (entries.length) {
document.body.innerHTML += "<p>异步的 requestIdleCallback() 回调先执行了"
}
})
requestAnimationFrame(() => {
setTimeout(() => {
if (observer.takeRecords().length) {
document.body.innerHTML += "<p>同步的 takeRecords() 先执行了"
}
}, 0)
})
observer.observe(document.body)
scrollTo(0, 1e10)
}, 100)
</script>
new IntersectionObserver(function(entries, observer) {
for (let entry of entries) {
console.log(entry.time)
console.log(entry.target)
console.log(entry.rootBounds)
console.log(entry.boundingClientRect
console.log(entry.intersectionRect)
console.log(entry.intersectionRatio)
}
})
<script>
let observer = new IntersectionObserver(([entry]) => {
document.body.textContent += `相交发生在 ${performance.now() - entry.time} 毫秒前`
})
observer.observe(document.documentElement)
</script>
{
"top": 0,
"bottom": 600,
"left": 0,
"right": 1280,
"width": 1280,
"height": 600
}
<div id="target"></div>
<script>
let observer = new IntersectionObserver(([entry]) => {
alert(entry.intersectionRatio)
})
observer.observe(target)
</script>
<div id="info">相交次数:
<span id="times">0</span>
<button onclick="document.scrollingElement.scrollTop = 10000">一下滚动到最低部</button>
</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: 200%;
width: 100px;
height: 100px;
background: red;
margin-bottom: 100px;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
times.textContent = +times.textContent + 1
}, {
threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] // 11 个临界值
})
observer.observe(target)
</script>
if (!target.isIntersecting) {
// 相交
target.isIntersecting = true
} else {
// 不想交
target.isIntersecting = false
}
<div id="info">不可见,请非常慢的向下滚动</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: 200%;
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(([entry]) => {
if (entry.intersectionRatio > 0) {
// 快速滚动会执行到这里
info.textContent = "可见了"
} else {
// 慢速滚动会执行到这里
info.textContent = "不可见,请非常慢的向下滚动"
}
})
observer.observe(target)
</script>
<div id="info">不可见,以任意速度向下滚动</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: 200%;
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(([entry]) => {
if (entry.intersectionRatio > 0) {
info.textContent = "可见了"
} else {
info.textContent = "不可见,以任意速度向下滚动"
}
}, {
threshold: [0.000001]
})
observer.observe(target)
</script>
<div id="root"></div>
<div id="target"></div>
<style>
#target {
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => alert("看见我了"), {root: root})
observer.observe(target) // target 此时并不是 root 的后代元素,Chrome 控制台会发出警告:target element is not a descendant of root.
root.appendChild(target) // 现在是了,触发回调
</script>
<div id="root"></div>
<style>
#target {
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => alert("看见我了"), {root: root})
let target = document.createElement("div") // 还不在 DOM 树里
observer.observe(target) // target 此时并不是 root 的后代元素,Chrome 控制台会发出警告:target element is not a descendant of root.
root.appendChild(target) // 现在是了,触发回调
</script>
<div id="a">
<div id="b"></div>
</div>
<div id="info">0%</div>
<style>
#a, #b {
position: fixed; /* 尝试改成 relative */
width: 200px;
height: 200px;
opacity: 0.8;
}
#a {
background: red
}
#b {
background: blue
}
#info {
width: 200px;
margin: 0 auto;
}
#info::before {
content: "Intersection Ratio: ";
}
</style>
<script>
let animate = (element, oldCoordinate = {x: 0, y: 0}) => {
let newCoordinate = {
x: Math.random() * (innerWidth - element.clientWidth),
y: Math.random() * (innerHeight - element.clientHeight)
}
let keyframes = [oldCoordinate, newCoordinate].map(coordinateToLeftTop)
let duration = calcDuration(oldCoordinate, newCoordinate)
element.animate(keyframes, duration).onfinish = () => animate(element, newCoordinate)
}
let coordinateToLeftTop = coordinate => ({
left: coordinate.x + "px",
top: coordinate.y + "px"
})
let calcDuration = (oldCoordinate, newCoordinate) => {
// 移动速度为 0.3 px/ms
return Math.hypot(oldCoordinate.x - newCoordinate.x, oldCoordinate.y - newCoordinate.y) / 0.3
}
animate(a)
animate(b)
</script>
<script>
let thresholds = Array.from({
length: 200
}, (k, v) => v / 200) // 200 个临界值对应 200px
new IntersectionObserver(([entry]) => {
info.textContent = (entry.intersectionRatio * 100).toFixed(2) + "%"
}, {
root: a,
threshold: thresholds
}).observe(b)
</script>
<div id="info"> 删除目标元素也会触发回调
<button onclick="document.body.removeChild(target)">删除 target</button>
</div>
<div id="target"></div>
<style>
#info {
position: fixed;
}
#target {
position: absolute;
top: 100px;
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
if (!document.getElementById("target")) {
info.textContent = "target 被删除了"
}
})
observer.observe(target)
</script>
<div id="root">
<iframe id="iframe"></iframe>
</div>
<script>
let iframeHTML = `
<div id="target"></div>
<style>
#target {
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
let observer = new IntersectionObserver(() => {
alert("intersecting")
}, {
root: top.root
})
observer.observe(target)
<\/script>`
iframe.src = URL.createObjectURL(new Blob([iframeHTML], {"type": "text/html"}))
</script>
<div id="parent">
<div id="target"></div>
</div>
<style>
#parent {
width: 20px;
height: 20px;
background: red;
overflow: hidden;
}
#target {
width: 100px;
height: 100px;
background: blue;
}
</style>
<script>
let observer = new IntersectionObserver(([entry]) => {
alert(`相交矩形为: ${entry.intersectionRect.width} x ${entry.intersectionRect.width}`)
})
observer.observe(target)
</script>
<div id="root"></div>
<div id="target"></div>
<script>
let observer = new IntersectionObserver(() => {}, {root: root}) // root 元素一共有两个引用,一个是 DOM 树里的引用,一个是全局变量 root 的引用
document.body.removeChild(root) // 从 DOM 树里移除
root = null // 全局变量置空
setTimeout(() => {
gc() // 手动 gc,需要在启动 Chrome 时传入 --js-flags='--expose-gc' 选项
console.log(observer.root) // null,观察者实例的根元素已经被垃圾回收了
observer.observe(target) // Uncaught InvalidStateError: observe() called on an IntersectionObserver with an invalid root,执行 observer 的任意方法都会报错。
})
</script>
setTimeout(() => {
let observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
console.log(entry.target) // 拿到了想要的宝贝元素
})
observer.disconnect() // 统计到就不在需要继续观察了
}, {
threshold: 0.5 // 只要展现面积达到 50% 的宝贝元素
})
// 观察所有的宝贝元素
Array.from(document.querySelectorAll("#mainsrp-itemlist .item")).forEach(item => observer.observe(item))
}, 2000)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有