javascript - 有没有办法修复一个没有 float 的div?

标签 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

最佳答案

添加

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

你在 .title 上没有任何左或右位置,所以它一开始看起来像是留在原地,但后来另一个元素将它推到右边

关于javascript - 有没有办法修复一个没有 float 的div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034455/

相关文章:

javascript - Facebook JS API : Any calls to FB. ui 返回错误代码:191

jquery - z-index 在某处被覆盖

javascript - 获取文本区域的值返回未定义

html - 使重叠 div 中的按钮可点击

jquery - 如何在错误回调函数中使用 jquery-jsonp 获取失败的 jsonp 请求的 HTTP 错误代码?

javascript - setCustomValidity Bootstrap 保持错误弹出

javascript - 如何使网页元素在全选命令中不突出显示

javascript - 如何定位 ajax 中类中正在单击的元素

javascript - Ext.js - 将时间戳格式化为 yyyy-mm-dd hh :mm:ss[. ffffffff]

javascript - 使用 .attr() 更新 Textarea 在输入和按键时增加++ 一行