Javascript 当静态元素与滚动条上的固定元素位置重叠时检测
如何正确检测静态元素何时与事件滚动上的固定元素y位置重叠 我肯定我以前做过,但现在我遗漏了一些东西(这里的例子) js: html:Javascript 当静态元素与滚动条上的固定元素位置重叠时检测,javascript,html,dom,Javascript,Html,Dom,如何正确检测静态元素何时与事件滚动上的固定元素y位置重叠 我肯定我以前做过,但现在我遗漏了一些东西(这里的例子) js: html: b将重叠a当其顶部位置小于a.top+a.height然后a.top大于b.top+b.height- var log=document.querySelector('.log'); window.addEventListener('scroll',函数(){ var b=document.querySelector('.b').getBoundingClien
b
将重叠a
当其顶部位置小于a.top+a.height
然后a.top
大于b.top+b.height
-
var log=document.querySelector('.log');
window.addEventListener('scroll',函数(){
var b=document.querySelector('.b').getBoundingClientRect(),
a=document.querySelector('.a').getBoundingClientRect();
如果(b.top a.top){
log.innerHTML='overlaps'
}否则{
log.innerHTML='不重叠'
}
});代码>
.a{
位置:固定;
宽度:50px;
高度:50px;
背景:红色;
顶部:50px;
}
.b{
边际上限:30vh;
宽度:50px;
高度:50px;
背景:蓝色;
}
身体{
高度:100vh;
}
.日志{
位置:固定;
顶部:50px;
左:80px;
}
b
将重叠a
当其顶部位置小于a.top+a.height
然后a.top
大于b.top+b.height
-
var log=document.querySelector('.log');
window.addEventListener('scroll',函数(){
var b=document.querySelector('.b').getBoundingClientRect(),
a=document.querySelector('.a').getBoundingClientRect();
如果(b.top a.top){
log.innerHTML='overlaps'
}否则{
log.innerHTML='不重叠'
}
});代码>
.a{
位置:固定;
宽度:50px;
高度:50px;
背景:红色;
顶部:50px;
}
.b{
边际上限:30vh;
宽度:50px;
高度:50px;
背景:蓝色;
}
身体{
高度:100vh;
}
.日志{
位置:固定;
顶部:50px;
左:80px;
}
谢谢@t1m0n这很有道理!我之所以使用滚动条是出于某种原因:PThanks@t1m0n这很有道理!我使用卷轴是出于某种原因:P
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)
*/
});
<div class="a"></div>
<div class="b"></div>
.a {
position: fixed;
width: 50px;
height: 50px;
background: red;
top: 50px;
}
.b {
margin-top: 30vh;
width: 50px;
height: 50px;
background: blue;
}
body {
height: 100vh;
}