console
$(document).ready(function(){
var io = new IntersectionObserver(function(entries){
entries.forEach(function(item){
var el = item.target;
if( item.isIntersecting ){
$(".watch-result").html(`触发threshold,可见比例: ${item.intersectionRatio}`);
// 停止观察
// io.unobserve(el);
}else{
$(".watch-result").html("看不见");
}
})
}, {
threshold: [0, 0.25, 1]
});
$(".watch-el").each(function(){
io.observe(this);
})
});
<div class="test-box">
<div class="watch-result"></div>
<div class="watch-el">
我是被观看的元素
</div>
</div>
body{
margin: 0;
}
.test-box{
position: relative;
min-height: 200vh;
color: #fff;
background:#666;
}
.test-box .watch-el{
position: absolute;
top: 50vh;
left: 50%;
border: 1px solid #fff;
height: 20vh;
line-height: 20vh;
}
.test-box .watch-result{
position: fixed;
top: 50vh;
left: 0;
color: #000;
background: #fff;
}