我正在创建一个标题,一旦滚动到一定数量的像素,它就会修复并保持在原位。
我可以只使用 css 和 html 来做到这一点还是我也需要 jquery?
我创建了一个演示,以便您可以理解。任何帮助都会很棒!
http://jsfiddle.net/gxRC9/4/
body{
margin:0px;
padding:0px;
}
.clear{
clear:both;
}
.container{
height:2000px;
}
.cover-photo-container{
width:700px;
height: 348px;
margin-bottom: 20px;
background-color:red;
}
.small-box{
width:163px;
height:100px;
border:1px solid blue;
float:left;
}
.sticky-header{
width:700px;
height:50px;
background:orange;
postion:fixed;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我修改了 Coop 的答案。请检查示例 FIDDLE 这是我的修改:
$(window).scroll(function(){ if ($(window).scrollTop() >= 330) { $('.sticky-header').addClass('fixed'); } else { $('.sticky-header').removeClass('fixed'); } });你需要一些 JS 来处理滚动事件。最好的方法是为固定位置设置一个新的 CSS 类,当滚动超过某个点时,该固定位置将分配给相关的 div。
HTML
CSS
.fixed { position: fixed; top:0; left:0; width: 100%; }jQuery
$(window).scroll(function(){ var sticky = $('.sticky'), scroll = $(window).scrollTop(); if (scroll >= 100) sticky.addClass('fixed'); else sticky.removeClass('fixed'); });小提琴示例:http://jsfiddle.net/gxRC9/501/
编辑:扩展示例
如果触发点未知,但应该在粘性元素到达屏幕顶部时触发,则可以使用
offset().top。var stickyOffset = $('.sticky').offset().top; $(window).scroll(function(){ var sticky = $('.sticky'), scroll = $(window).scrollTop(); if (scroll >= stickyOffset) sticky.addClass('fixed'); else sticky.removeClass('fixed'); });扩展示例小提琴:http://jsfiddle.net/gxRC9/502/