2

当一个 div 在滚动时悬停在另一个 div 上时,如何发出警报?这是一个工作示例, http://jsfiddle.net/uprosoft/Ek5Gy/267/

虽然为了发出警报,但我找不到要跟踪的 jQuery 代码。

代码:

HTML

<div id="container">
<div id="div1">test</div>
<br>
<div id="div2"> another test</div>
</div>

CSS

#div1{
background: green;
position: fixed;
        width: 100%;
}
#div2{
background: yellow;
position: relative;
width: 100%;
margin-top: 100px;
}
#container{

height: 1000px;

}

查询 ???

/* what jquery code goes here? to alert when the yellow div touches the green div upon scroll? */
4

2 回答 2

4

像这样的东西应该工作:

$(window).scroll(function() {
    var div1 = $("#div1");
    var div2 = $("#div2");
    var div1_top = div1.offset().top;
    var div2_top = div2.offset().top;
    var div1_bottom = div1_top + div1.height();
    var div2_bottom = div2_top + div2.height();

    if (div1_bottom >= div2_top && div1_top < div2_bottom) {
        // overlapped
    }
});​

演示:http: //jsfiddle.net/Ek5Gy/280/

于 2012-06-25T16:30:36.047 回答
0

我知道问题是针对 Jquery 的,但不管怎样,vanilla JS 也是如此

function didDiv1TouchedDiv2() {
    var div1 = document.getElementById("div1"); 
    var div2 = document.getElementById("div2"); 
    // Guard
    if (div1 === undefined || div2 === undefined) return;
    var div1Rect = div1.getBoundingClientRect();
    var div2Rect = div2.getBoundingClientRect();
    // We need to add the offsetHeight in order to include padding and border of element and get excact position
    return div1Rect.top >= div2Rect.top + div2.offsetHeight;  
}
window.addEventListener("scroll", didDiv1TouchedDiv2);
于 2021-11-29T19:33:04.980 回答