有没有办法修复div没有它漂浮正确?

时间:2014-01-10 01:10:38

标签: javascript jquery html css

当我滚动时,我试图使用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

2 个答案:

答案 0 :(得分:0)

添加

$('.title').css("right", "100px");  //or however much works in px or %

你在.title上没有任何左或右位置,所以看起来它最初会保持原位,但是然后另一个元素将它推到右边

答案 1 :(得分:0)

为什么要使用jQuery呢?只需使用CSS来修复位置:

.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;
    position: fixed;
    top: 0;
}

JS小提琴: http://jsfiddle.net/d3Z84/