在顶部相对于div容器修复标题

时间:2014-04-09 16:20:59

标签: javascript jquery html css

我在顶部修复标题时遇到问题。标题位于容器div中,即使容器div已滚动,我也希望它保持在顶部。

HTML:

<div class="wrapper">
    <div class="container">
        <div class="fixed">
            SHOULD BE FIXED
        </div>
    </div>
</div>

CSS:

.wrapper{
    width:300px;
    height:200px;
    margin:auto;
    border:1px solid #ddd;
    overflow-y:scroll;
    overflow-x:hidden;
}
.container{
    width:300px;
    position:relative;
    height:1000px;
    background:#111;
}
.fixed{
    background:#aaa;
    position:absolute;
    height:50px;
    width:100%;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

这是 fiddle

3 个答案:

答案 0 :(得分:2)

样式position: fixed是要走的路:

.fixed {
    position: fixed;
    width: inherit;
}

DEMO: http://jsfiddle.net/F2Fhd/3/

答案 1 :(得分:0)

更改.fixed css位置:绝对位置:固定并将宽度设置为300px! :)

CSS:

.fixed{
    background:#aaa;
    position:fixed;
    height:50px;
    width:300px;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

http://jsfiddle.net/F2Fhd/4/

答案 2 :(得分:-1)

尝试使用jquery以更友好的方式使用浏览器。

<script>
$(document).ready(function() {
var div = $('**.fixed**');
var start = $(div).offset().top;
$.event.add(window, "scroll", function() {
    var ul = $(window).scrollTop();
    $(div).css('position',((ul)>start) ? 'fixed' : '');
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 2000);
        return false;
    }
}
});
</script>