请检查小提琴: http://jsfiddle.net/howtoplease/f8sXN/4/
滚动时,我想通过jQuery将.float
粘贴到.right
。
HTML代码
<div class="main">
<div class="float">
float
</div>
<div class="right">
Stick float to me
</div>
</div>
CSS代码
.main{
margin-bottom:30px;
}
.float{
background: #333333;
color: #FFFFFF;
float: left;
height: 40px;
margin-right: 20px;
width: 40px;
}
.right{
background: none repeat scroll 0 0 #AAAAAA;
height: 245px;
overflow: hidden;
}
答案 0 :(得分:2)
这应该做:
$(window).scroll(function(){
var st = $(this).scrollTop();
$('.main').each(function(){
var $this = $(this),
offset = $this.offset(),
h = $this.height(),
$float = $this.find('.float'),
floatH = $float.height();
if(st >= offset.top && st < offset.top + h - floatH){
$float.css({'position':'fixed'});
}else{
$float.css({'position':'absolute'});
}
})
});
CSS:
.main{
margin-bottom:30px;
/* set main to realtive so float won't move out bounds */
position:relative;
}
.float{
background: #333333;
color: #FFFFFF;
height: 40px;
width: 40px;
/* set top to 0 and position to absolute*/
top:0;
position:absolute;
}
.right{
background: none repeat scroll 0 0 #AAAAAA;
height: 245px;
overflow: hidden;
/* the float width:40 plus its margin-right:20 that I removed*/
margin-left:60px;
}
我已经更新了解决'.right'
问题的答案 - 保持相同的宽度和位置。
与@UDB解决方案类似,但在该方法上(更改'margin-top'
)我注意到'.float'
有时会在长滚动时发抖并快速滚动这种情况:
在我的新解决方案中,我们只更改position
属性,因此到目前为止没有问题。
请参阅此jsfiddle。
还要感谢@Zeaklous和@UDB的想法。
答案 1 :(得分:0)
更改了Mark S
的答案,将.float
保留在左侧,就像评论中提供了链接的页面一样
$(window).scroll(function () {
var st = $(this).scrollTop();
$('.main').each(function () {
var $this = $(this),
offset = $this.offset(),
h = $this.height();
if (st >= offset.top && st < offset.top + h - 40) {
$this.find('.float').css({
'margin-top': st - offset.top + 'px'
});
} else if (st >= offset.top + h + 30/*.main margin-bottom*/) {
$this.find('.float').css({
'margin-top': 'auto'
});
}
})
});