-->

Detect when static element overlaps fixed element

2020-08-09 05:54发布

问题:

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;
}

回答1:

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>