[英]Prevent div from scrolling over another div
我有以下代碼:
<div id="header">
Header
</div>
<div id="leftside">
Left Side
<!--A lot of text here.-->
</div>
<div id="right-container">
<div id="one">
One
</div>
<div id="two">
Two
</div>
</div>
<div id="footer">
Footer
</div>
#header {
background-color: blue;
color: white;
width: 80%;
height: 100px;
padding: 5px;
}
#leftside {
display: inline-block;
background-color: purple;
color: white;
width: 39%;
padding: 5px;
vertical-align: top;
}
#right-container {
display: inline-block;
background-color: green;
color: white;
width: 39%;
padding: 5px;
}
body{height:400px;}
#one {
background-color: yellow;
color: white;
width: 97%;
height: 50px;
padding: 5px;
}
#two{
background-color: orange;
color: white;
width: 37%;
height: 500px;
padding: 5px;
position: fixed;
}
#footer {
background-color: grey;
color: white;
width: 80%;
height: 500px;
padding: 5px;
}
$(document).scroll(function() {
var $self = $("#two");
$self.css('margin-top', 0);
var twoOffset = $self.offset().top + $self.outerHeight(true);
if (twoOffset > ($("#footer").offset().top - 30)) {
$self.css('margin-top', -(twoOffset - $("#footer").offset().top));
} else {
$self.css('margin-top', '30px');
}
});
該腳本可防止div( id="two"
)在footer
div上滾動。
但我也想防止div( id="two"
id="one"
)直接在其上方的div( id="one"
)上滾動,就像您在此JSFIDDLE中看到的那樣 。
我猜可以使用相同的腳本,但是我嘗試不成功地對其進行修改。 你能幫忙嗎?
var i = $('#one').offset().top;
var x = $('#two').offset().top;
var y = $('window').scrollTop();
$(window).scroll(function(){
$(this).scrollTop(function(){
if (y <= y || x <= i) {
$('#two').css('position','static');
}
});
});
您正確的容器似乎被弄亂了。 我建議您使用http://leafo.net/sticky-kit/並執行
$("#two").stick_in_parent();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.