2016-05-06 146 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 { 
    position: fixed; 
    width: 50px; 
    height: 50px; 
    background: red; 
    top: 50px; 
} 
.b { 
    margin-top: 30vh; 
    width: 50px; 
    height: 50px; 
    background: blue; 
} 

body { 
    height: 100vh; 
} 

回答

2

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(); 
 
    
 
    
 
    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

感謝@ t1m0n有道理!我出於某種原因使用了scrollY:P – punkbit