我想创建一个 div,它位于内容块下方,但是一旦页面滚动到足以接触其顶部边界,它就会固定在适当的位置并随页面滚动。
您可以简单地使用 css,将元素定位为fixed https://developer.mozilla.org/en-US/docs/Web/CSS/position:
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
Edit:您应该拥有绝对位置的元素,一旦滚动偏移到达该元素,就应该将其更改为固定,并且顶部位置应设置为零。
您可以使用以下命令检测文档的顶部滚动偏移量滚动顶部 http://docs.jquery.com/CSS/scrollTop功能:
$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});
当滚动偏移达到200时,元素将stick到浏览器窗口的顶部,因为放置为固定的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)