2016-05-06 4 views
0

静的要素がイベントのスクロールで固定要素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.top + a.height次いで少なくなり、次いでa.topが次に大きい場合

.a { 
    position: fixed; 
    width: 50px; 
    height: 50px; 
    background: red; 
    top: 50px; 
} 
.b { 
    margin-top: 30vh; 
    width: 50px; 
    height: 50px; 
    background: blue; 
} 

body { 
    height: 100vh; 
} 

答えて

2

baを重複しますb.top + b.height - 理にかなってt1m0n @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>

+0

ありがとう!私は何らかの理由でscrollYを使用していました:P – punkbit

関連する問題