我有.container
div有一些内容和一个隐藏的标题,这个元素也有overflow-Y: auto;
属性。当用户在.container
左右滚动到100px
左右时,我想使标题固定。如何使一个元素固定但相对于它的父级滚动?
这里是我的代码:
.container {position: relative; border: 1px solid #ccc; overflow-y: auto; height: 200px; margin-top: 50px; width: 500px;}
.to-be-fixed {position: absolute; top: 0px; left: 0px; height: 30px; text-align: center; font-family: Arial; padding: 0px 12px; background: red; width: 100%; line-height: 30px; margin-top: -30px;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
\t <div class="to-be-fixed">
\t \t Header to be fixed
\t </div>
\t <div class="content-holder">
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t \t <p>content here..!</p>
\t </div>
</div>
当我不使用头margin-top: -30px;
它正在显示...!像这样的图片:
我想它应该是只显示当用户向下滚动,以查看container
元素这样的形象更多的内容:
我也用了一些jQuery使其固定,但它不工作:
$(document).ready(function(){
var headerFixed = $('.to-be-fixed');
var headerFixedHolder = $('.container');
var heightScrolled = headerFixed .offset().top - headerFixedHolder .offset().top;
if (heightScrolled > 100) {
$('.to-be-fixed').css('position', 'fixed');
}
});
虽然我k现在css()方法中的css属性将无法正常工作,但我不知道该怎么办......! 请帮我..!
真的好...!但还需要做一件事,即在滚动到容器之前应隐藏标题。 –
你见过同样的输出吗!请参阅一次agine,它现在不工作..! –
真的很好,有帮助的工作..!谢谢@Mihai T. –