我想创建一个div,它位于内容块下方,但一旦页面滚动到足够接触其顶部边界,它就会固定在原地并随着页面滚动。
我想创建一个div,它位于内容块下方,但一旦页面滚动到足够接触其顶部边界,它就会固定在原地并随着页面滚动。
你可以简单地使用CSS,将你的元素定位为fixed:
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
编辑:当滚动偏移量到达元素时,应将该元素位置设置为absolute,然后更改为fixed,并将顶部位置设置为零。
您可以使用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时,该元素将会在浏览器窗口顶部固定,因为它的定位是fixed。
if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed') { $('.fixedElement').css({'position': 'static', 'top': '0px'}); }
- Derrick Petzoldnew example
链接太干净清晰了,我甚至都看不到它!-_- - sohaiby你在Google Code的问题页面上看到了这个例子,最近也出现在Stack Overflow的编辑页面上。
CMS的答案没有在向上滚动时恢复位置。以下是从Stack Overflow不要脸地偷来的代码:
function moveScroller() {
var $anchor = $("#scroller-anchor");
var $scroller = $('#scroller');
var move = function() {
var st = $(window).scrollTop();
var ot = $anchor.offset().top;
if(st > ot) {
$scroller.css({
position: "fixed",
top: "0px"
});
} else {
$scroller.css({
position: "relative",
top: ""
});
}
};
$(window).scroll(move);
move();
}
<div id="sidebar" style="width:270px;">
<div id="scroller-anchor"></div>
<div id="scroller" style="margin-top:10px; width:270px">
Scroller Scroller Scroller
</div>
</div>
<script type="text/javascript">
$(function() {
moveScroller();
});
</script>
这里有一个简单的在线演示。
一种新出现的、无需使用脚本的替代方案是position: sticky
,它在Chrome、Firefox和Safari中都得到了支持。请参考HTML5Rocks上的文章以及演示和Mozilla文档。
offset
必须已经停止接受对象作为输入http://api.jquery.com/offset/. @Eddie 您的修改应该在当前的jQuery中是安全的。 - Graemevar d = $(“#sidebar”).offset()。top;
替换var d = $(“#scroller-anchor”).offset()。top;
并完全摆脱空的滚动锚点div?这是我的fork,演示了我所说的。 - Mike Deck截至2017年1月和Chrome 56的发布,大多数常用浏览器都支持CSS中的position: sticky
属性。
#thing_to_stick {
position: sticky;
top: 0;
}
在Firefox和Chrome中,这对我很有用。
在Safari中,您仍然需要使用position: -webkit-sticky
。
Internet Explorer和Edge可以使用Polyfills; https://github.com/wilddeer/stickyfill似乎是一个不错的选择。
top: 0;
。 - Akaisteph7以下是没有使用jQuery的方法(更新:请查看其他答案,现在可以只用CSS完成此操作)
var startProductBarPos=-1;
window.onscroll=function(){
var bar = document.getElementById('nav');
if(startProductBarPos<0)startProductBarPos=findPosY(bar);
if(pageYOffset>startProductBarPos){
bar.style.position='fixed';
bar.style.top=0;
}else{
bar.style.position='relative';
}
};
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
}
else if (obj.y)
curtop += obj.y;
return curtop;
}
* {margin:0;padding:0;}
.nav {
border: 1px red dashed;
background: #00ffff;
text-align:center;
padding: 21px 0;
margin: 0 auto;
z-index:10;
width:100%;
left:0;
right:0;
}
.header {
text-align:center;
padding: 65px 0;
border: 1px red dashed;
}
.content {
padding: 500px 0;
text-align:center;
border: 1px red dashed;
}
.footer {
padding: 100px 0;
text-align:center;
background: #777;
border: 1px red dashed;
}
<header class="header">This is a Header</header>
<div id="nav" class="nav">Main Navigation</div>
<div class="content">Hello World!</div>
<footer class="footer">This is a Footer</footer>
padding-top
,就更容易看到。演示:https://jsbin.com/fivugux/edit?html,css,js,output - Mosh Feu我曾经和你一样遇到了同样的问题,最终我制作了一个jQuery插件来解决它。实际上,它解决了人们在这里列出的所有问题,还添加了一些可选功能。
stickyPanelSettings = {
// Use this to set the top margin of the detached panel.
topPadding: 0,
// This class is applied when the panel detaches.
afterDetachCSSClass: "",
// When set to true the space where the panel was is kept open.
savePanelSpace: false,
// Event fires when panel is detached
// function(detachedPanel, panelSpacer){....}
onDetached: null,
// Event fires when panel is reattached
// function(detachedPanel){....}
onReAttached: null,
// Set this using any valid jquery selector to
// set the parent of the sticky panel.
// If set to null then the window object will be used.
parentSelector: null
};
code
// 分离面板
node.css({
"margin": 0,
"left": nodeLeft,
"top": newNodeTop,
"position": "fixed",
"width": node.width()
});code
- Will Hancock.container {
position: relative;
}
.sticky-div {
position: sticky;
top: 0;
}
<div class="container">
<h1>
relative container & sticky div
</h1>
<div class="sticky-div"> this row is sticky</div>
<div>
content
</div>
</div>
position: relative
。 - Mosh Feu这是我使用jQuery实现的方法。这个解决方案是从Stack Overflow上的各种答案中拼凑而成的。该解决方案缓存选择器以提高性能,并解决了粘性div变为sticky时出现的“跳跃”问题。
在jsfiddle上查看:http://jsfiddle.net/HQS8s/
CSS:
.stick {
position: fixed;
top: 0;
}
JS:
$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
$mainMenuBar = $('#mainMenuBar'),
$mainMenuBarAnchor = $('#mainMenuBarAnchor');
// Run this on scroll events.
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('stick');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div.
$mainMenuBar.removeClass('stick');
$mainMenuBarAnchor.height(0);
}
});
});
position: sticky; top: 0;
应用于你想要滚动的div...<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>
只需将#sticky_div's_name_here
替换为您的div的名称,即如果您的div是<div id="example">
,则应该放置#example { position: sticky; top: 0; }
。
这里还有另一种选择:
JAVASCRIPT
var initTopPosition= $('#myElementToStick').offset().top;
$(window).scroll(function(){
if($(window).scrollTop() > initTopPosition)
$('#myElementToStick').css({'position':'fixed','top':'0px'});
else
$('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});
你的#myElementToStick
应该以position:absolute
CSS属性开始。
.sticky { position:fixed; top:0; }
JQuery:
function make_sticky(id) {
var e = $(id);
var w = $(window);
$('<div/>').insertBefore(id);
$('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
var n = e.next();
var p = e.prev();
function sticky_relocate() {
var window_top = w.scrollTop();
var div_top = p.offset().top;
if (window_top > div_top) {
e.addClass('sticky');
n.show();
} else {
e.removeClass('sticky');
n.hide();
}
}
w.scroll(sticky_relocate);
sticky_relocate();
}
make_sticky('#sticky-elem-id');
position: sticky; top:0;
在大多数浏览器中都能正常工作。 - Colin 't Hartposition: sticky;
的东西真是神奇。 - tscizzlerelative
容器中,position: sticky; top:0;
对我有效。 - Marzieh Mousavi