Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

javascript - 滚动到后,如何使div停留在屏幕顶部?(How can I make a div stick to the top of the screen once it's been scrolled to?)

我想创建一个div,它位于内容块的下面,但是一旦页面滚动到足以接触其顶部边界的位置,它就会固定在适当的位置并随页面滚动。

  ask by evanr translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use simply css, positioning your element as fixed :(您可以简单地使用css,将元素定位为fixed :)

.fixedElement { background-color: #c0c0c0; position:fixed; top:0; width:100%; z-index:100; } Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.(编辑:您应该将元素的位置设为绝对,一旦滚动偏移量到达该元素,则应将其更改为fixed,并将顶部位置设置为零。) You can detect the top scroll offset of the document with the scrollTop function:(您可以使用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'}); } }); When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.(当滚动偏移量达到200时,该元素将固定在浏览器窗口的顶部,因为它的位置固定。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...