[英]jQuery function that returns when a div touches another div upon scroll
how can I give an alert when one div hovers over another div upon scroll?当一个 div 在滚动时悬停在另一个 div 上时,如何发出警报? here is a working example, http://jsfiddle.net/uprosoft/Ek5Gy/267/这是一个工作示例, http://jsfiddle.net/uprosoft/Ek5Gy/267/
I cant find a jQuery code to go after though in-order to give an alert.我无法找到一个 jQuery 代码来发出警报。
HTML HTML
<div id="container">
<div id="div1">test</div>
<br>
<div id="div2"> another test</div>
</div>
CSS CSS
#div1{
background: green;
position: fixed;
width: 100%;
}
#div2{
background: yellow;
position: relative;
width: 100%;
margin-top: 100px;
}
#container{
height: 1000px;
}
JQUERY ???查询 ???
/* what jquery code goes here? to alert when the yellow div touches the green div upon scroll? */
Something like that should work: 这样的东西应该工作:
$(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
}
});
DEMO: http://jsfiddle.net/Ek5Gy/280/ 演示: http : //jsfiddle.net/Ek5Gy/280/
I know the question is for Jquery but either way, the same done with vanilla JS我知道这个问题是针对 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.