我正在尝试使用 jquery 在滚动时将一个 div 固定到屏幕顶部。
然而,当它到达顶部时,它会漂浮到窗口的右侧,而不是留在原地。
.title{
font-size:200%;
background-color:#282C2F;
color: #EFEFEF;
width:100%;
text-align: center;
font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
border-radius:2px;
opacity:.8;
}
<div class="title">
Timeline: Penguins in the city
</div>
JavaScript
var titlePosition = $('.title').offset() //find timeline title position
var titleWidth = $('.title').width() //find time line title width
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
if (scrollBar > titlePosition.top) { //a play on offset().top which finds top postion of an element
$('.title').css("top","0px");
$('.title').css("position","fixed");
$('.title').css("width",titleWidth); //this is important...it makes the width of our newly fixed div stay the same.
} else {
$('.title').css("position","relative");
};
}); //end of scroll function
最佳答案
添加
$('.title').css("right", "100px"); //or however much works in px or %
你在 .title 上没有任何左或右位置,所以它一开始看起来像是留在原地,但后来另一个元素将它推到右边
关于javascript - 有没有办法修复一个没有 float 的div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034455/