检测静态元素何时与滚动上的固定元素位置重叠 [英] Detect when static element overlaps fixed element position on scroll
问题描述
如何正确检测静态元素何时与事件滚动上的固定元素y位置重叠?
我确定我之前已经做过,但是在一会儿我错过了一些东西(例如此处的示例 http://jsbin.com/hetovoduwi/edit? css,js,控制台,输出)。
js:
window.addEventListener('scroll',function(){
console.log('win y:'+ window.scrollY);
var b = document.querySelector( '.b')。getBoundingClientRect();
console.log(b);
/ *
console.log('(b.top + b .height)',(b.top + b.height));
console.log('window.scrollY-50',window.scrollY-50)
* /
});
html:
< div class = a>< / div>
< div class = b>< / div>
css:
.a {
头寸:固定;
宽度:50像素;
高度:50像素;
背景:红色;
top:50像素;
}
.b {
margin-top:30vh;
宽度:50像素;
高度:50像素;
背景:蓝色;
}
body {
身高:100vh;
}
b
与 a
重叠时,其顶部位置将小于 a.top + a.height
,然后 a.top
更大,然后 b.top + b.height
- http://jsbin.com/peqiximugo/1/edit?css,js,console,output
var log = document.querySelector('。log'); window.addEventListener('scroll',function(){var b = document.querySelector('。b')。getBoundingClientRect(),a = document.querySelector('。a')。getBoundingClientRect();如果(b.top< = a.top + a.height& b.top + b.height> a.top){log.innerHTML ='overlaps'} else {log.innerHTML ='不重叠'}});
.a {位置:固定;宽度:50像素;高度:50px;背景:红色; top:50px;}。b {margin-top:30vh;宽度:50像素;高度:50px;背景:蓝色;} body {高度:100vh;}。log {位置:固定;顶部:50px;左:80px;}
< div class = a >< / div>< div class = b>< / div>< div class ='log'>< / div>
How to properly detect when a static element overlaps a fixed element y position on event scroll ?
I'm sure I've done this before, but at the moment I missing something (example here http://jsbin.com/hetovoduwi/edit?css,js,console,output).
js:
window.addEventListener('scroll', function () {
console.log('win y:' + window.scrollY);
var b = document.querySelector('.b').getBoundingClientRect();
console.log(b);
/*
console.log('(b.top+b.height)', (b.top+b.height));
console.log('window.scrollY - 50', window.scrollY - 50)
*/
});
html:
<div class="a"></div>
<div class="b"></div>
css:
.a {
position: fixed;
width: 50px;
height: 50px;
background: red;
top: 50px;
}
.b {
margin-top: 30vh;
width: 50px;
height: 50px;
background: blue;
}
body {
height: 100vh;
}
b
will overlap a
when its top position will be less then a.top + a.height
and then a.top
is bigger then b.top + b.height
- http://jsbin.com/peqiximugo/1/edit?css,js,console,output
var log = document.querySelector('.log');
window.addEventListener('scroll', function () {
var b = document.querySelector('.b').getBoundingClientRect(),
a = document.querySelector('.a').getBoundingClientRect();
if (b.top <= a.top + a.height && b.top + b.height > a.top) {
log.innerHTML = 'overlaps'
} else {
log.innerHTML = 'doesn\'t overlaps'
}
});
.a {
position: fixed;
width: 50px;
height: 50px;
background: red;
top: 50px;
}
.b {
margin-top: 30vh;
width: 50px;
height: 50px;
background: blue;
}
body {
height: 100vh;
}
.log {
position: fixed;
top: 50px;
left: 80px;
}
<div class="a"></div>
<div class="b"></div>
<div class='log'></div>
这篇关于检测静态元素何时与滚动上的固定元素位置重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!