当一个div被滚动到屏幕顶部时,我如何才能将它固定在屏幕顶部呢?我想要创建一个div,它位于一个内容块下面,但是一旦页面被滚动到足以与其顶部边界联系起来,就会固定在适当的位置,并与页面一起滚动。
3 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;}编辑:
$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
} });
猛跑小猪
TA贡献1858条经验 获得超8个赞
function moveScroller() {
var $anchor = $("#scroller-anchor");
var $scroller = $('#scroller');
var move = function() {
var st = $(window).scrollTop();
var ot = $anchor.offset().top;
if(st > ot) {
$scroller.css({
position: "fixed",
top: "0px"
});
} else {
$scroller.css({
position: "relative",
top: ""
});
}
};
$(window).scroll(move);
move();}<div id="sidebar" style="width:270px;">
<div id="scroller-anchor"></div>
<div id="scroller" style="margin-top:10px; width:270px">
Scroller Scroller Scroller </div></div><script type="text/javascript">
$(function() {
moveScroller();
});</script>position: sticky
添加回答
举报
0/150
提交
取消
