检测静态元素何时与滚动上的固定元素位置重叠

时间:2016-05-06 12:40:18

标签: javascript html dom

如何正确检测静态元素何时与事件滚动中的固定元素y位置重叠?

我确定我之前已经这样做了,但此刻我遗漏了一些东西(例如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;
}

1 个答案:

答案 0 :(得分:2)

b的最高位置小于a,然后a.top + a.height大于a.top - http://jsbin.com/peqiximugo/1/edit?css,js,console,output < / p>

&#13;
&#13;
b.top + b.height
&#13;
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'
  }

});
&#13;
.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;
}
&#13;
&#13;
&#13;