对需要固定的div添加样式
#opr_fixed{
//自定义样式
padding-top: 12px;
padding-bottom: 12px;
background: #fff;
//固定写法
width: 100%;
top: 0px;
position: relative;
}
结合jquery 进行控制:
window.onload = function () {
var pos = $('#opr_fixed').offset();// offset() 获得div1当前的位置,左上角坐标(x,y)
$(window).scroll(function () { //滚动条滚动事件
if ($(this).scrollTop() > pos.top ) {
$('#opr_fixed').css('width', '100%').css('top', $(this).scrollTop() - pos.top);
}
else if ($(this).scrollTop() <= pos.top ) {
$('#opr_fixed').css('width', '100%').css('top',0).css('position', 'relative');
}
})
};
本文介绍了一种使用CSS和jQuery实现div元素固定位置的方法。通过定义特定的样式,如padding和背景颜色,并利用jQuery监听滚动事件,可以实现在页面滚动时div元素位置的动态调整。文章详细解释了如何使用offset()和scrollTop()方法来判断和设置div元素的位置。

1251

被折叠的 条评论
为什么被折叠?



