我正在创建一个标头,一旦滚动到一定数量的像素,它就会固定并保持在原位。
我可以仅使用CSS和HTML来执行此操作吗,还是也需要jquery?
我创建了一个演示,以便您可以理解。任何帮助将是巨大的!
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;
}
您需要一些JS来进行滚动事件。最好的方法是为固定位置设置一个新的CSS类,当滚动超过特定点时,该类将分配给相关的div。
的HTML
<div class="sticky"></div>
的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/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句