我需要在容器内有一个 float 的 div。当我移动滚动条时,它应该在指定的容器 div 内相应移动。我在这里发现了类似的东西:http://www.mkyong.com/jquery/mashable-floating-effect-example-with-jquery/但在我的情况下,它需要 float 在另一个 div/容器内,并且它应该粘在页面的底部。例如,当我从底部滚动到顶部时, float div 不应该向上移动,直到浏览器窗口的底部“接触”它,然后它应该开始移动,直到我到达容器 div 顶部的顶部。
我在这里找到了另一个例子:Spotlight: Constrained Stickies with jQuery 但这也会在包含元素的顶部启动 float 元素。不知道如何修改。
这是我到目前为止所拥有的:http://jsfiddle.net/CCpJg/25/
谢谢
以下是 William Niu 的解决方案:(链接如下)
HTML:
<div id="page">
<div id="header"><h1>header</h1></div>
<div id="body">
<h1>content top -> when scrolling up the box should STOP here (at the line right above this text)</h1>
<div id="floating-box"></div>
<span style="position: absolute; bottom: 0; ">content bottom -> when scrolling down the box should STOP here (at the line right below this text)</span>
</div>
<div id="footer"><h1>footer</h1></div>
<div id="debug"></div>
</div>
CSS:
#floating-box{
width:90px;
height:200px;
border:1px solid red;
background-color:#BBBBBB;
position:absolute;
bottom: 0;
z-index:1;
}
#page{
width:800px;
margin:0 auto;
}
#header{
border:1px solid blue;
height:1010px;
margin:8px;
}
#body{
border:1px solid blue;
height:540px;
margin:8px;
position: relative;
}
#footer{
border:1px solid blue;
height:1500px;
margin:8px;
}
h1,h2{
padding:16px;
}
#debug {
position: fixed;
bottom: 0;
right: 0;
height: 100px;
width: 100px;
color: red;
}
jQuery:
var windowHeight = $(window).height();
var $box = $('#floating-box');
var $parent = $('#body');
var parentAbsoluteTop = $parent.offset().top;
var parentAbsoluteBottom = parentAbsoluteTop + $parent.height();
var topStop = parentAbsoluteTop + $box.height();
$(window).scroll(function(event) {
var windowBottom = $(window).scrollTop() + windowHeight;
if (windowBottom < topStop)
$box.css({
position: 'absolute',
top: '0px',
bottom: 'auto'
});
else if (windowBottom >= topStop && windowBottom <= parentAbsoluteBottom)
$box.css({
position: 'fixed',
top: 'auto',
bottom: '0px'
});
else
$box.css({
position: 'absolute',
top: 'auto',
bottom: '0px'
});
});
最佳答案
看看这个从您提供的演示修改而来的演示:http://jsfiddle.net/CCpJg/32/
关于jquery - 容器内的底部 float div(如 Facebook 消息中) - 采取 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6591803/