Javascript 在顶部相对于div容器固定一个标题

Javascript 在顶部相对于div容器固定一个标题,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我在固定顶部的收割台时遇到问题。标题在容器div中,我希望它保持在顶部,即使容器div被滚动 HTML: <div class="wrapper"> <div class="container"> <div class="fixed"> SHOULD BE FIXED </div> </div> </div> 这里有一个风格位置:固定的是一种方式: .

我在固定顶部的收割台时遇到问题。标题在容器div中,我希望它保持在顶部,即使容器div被滚动

HTML:

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

这里有一个风格
位置:固定的
是一种方式:

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

演示:更改。固定类位置:绝对位置:固定并将宽度设置为300px!:)

CSS:


尝试使用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>

$(文档).ready(函数(){
var div=$('**.fixed**');
var start=$(div).offset().top;
$.event.add(窗口,“滚动”,函数(){
var ul=$(window.scrollTop();
$(div).css('position',((ul)>start)?'fixed':'';
});
});
$('a[href*=#]:非([href=#])。单击(函数(){
if(location.pathname.replace(/^\/,“”)=此.pathname.replace(/^\/,“”)
||location.hostname==this.hostname){
var target=$(this.hash);
target=target.length?target:$('[name='+this.hash.slice(1)+']');
if(目标长度){
$('html,body')。设置动画({
scrollTop:target.offset().top
}, 2000);
返回false;
}
}
});

只需在之前或之后添加一些内容,就可以解决问题。我不知道
width:inherit
,我正在尝试
width:100%
,这导致固定div扩展到浏览器的宽度。顺便说一句:)@AamirAfridi为什么不将容器的宽度更改为
30000px
?你的案例是一个完全不同的问题,情况不同。@RokoC.Buljan真棒的名字!然而,背后的代码并不性感,因为你必须使用JS,因为一旦你将一个元素设置为固定,它就变成了一个不值得触摸的便便,而是一根棍子(JavaStick:D),因为他们还没有发明一些更动态的CSS计算,比如
calc(inherit-17px).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;
}
<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>