包含的粘性边栏
我需要一个侧边栏,当用户在页面上滚动时,该边栏会与固定位置保持一致。我遇到了很多解决方案,都非常笨重,复杂或太长。我需要它简单而高效。我想它并使它:包含的粘性边栏
var length = $('#container').height() - $('#stick').offset().top - parseFloat($('#stick').css('marginTop').replace(/auto/, 0));
$(window).scroll(function() {
var scroll = $(this).scrollTop();
if (scroll < $('#container').offset().top) {
$('#stick').removeAttr("style");
}
else if (scroll > length) {
$('#stick').css('position', 'absolute');
}
else {
$('#stick').css({"position":"fixed", "top":"0", "right":"0"});
}
});
我的Remy Sharp screencast的帮助和waypointarts blog post
当#container的获得在视口的末端#stick停止滚动做这个(“固定”的位置被移除),问题是它消失了,并没有保持在该位置的绝对位置,这种行为会干扰用户。
如何让#stick侧栏完全定位在#container的底部而不是消失?你是否也认为我的代码可以完善?
我是业余的,并开始使用jquery1个月现在,所以你会发现很多在这里的错误...
谢谢。
我设法做到了。我不知道为什么它会被贬低,但是我决定不直接将css属性注入到html中,而是使用更适合css的方法,在实际的css文件中应用css,因为html应该使用html语言。
所以这个想法我添加了CSS类与jQuery的行动和在CSS中我添加了这些类我想要的样式,并且一切工作都很完美。也许这是一些重叠的CSS规则,之前做了一些错误......无论如何,它有更好的方法,它的格式更好。
所以,在html:
<body>
<header>The header</header>
<main id="container">
<article id="content">Main content</article>
<section id="sticky">Sticking content</section>
</main>
<footer>The footer</footer>
<body>
jQuery的:
var $container = $('#container');
var $sticky = $('#sticky');
var length = $container.height() + $container.offset().top - $sticky.height();
$(window).scroll(function() {
var y = $(this).scrollTop();
if (y < $container.offset().top) { $sticky.removeClass('sticky-fixed sticky-bottom'); }
else if (y > length) { $sticky.attr('class','sticky sticky-bottom'); }
else { $sticky.attr('class','sticky sticky-fixed'); }
});
的CSS:
#sticky {
width: 260px;
position: absolute;
right: 0;
top: 128px;
}
#sticky-fixed {
position: fixed;
right: 0;
top: 128px;
}
#sticky-bottom {
position: absolute;
right: 0;
bottom: 0;
top: auto;
}
这里做的事情:
如果页面位于顶部#sticky将具有“绝对位置”,当用户开始滚动页面时,它将具有“位置固定”(始终在内容的侧面可见),并且当视点到达底部时#container,其中的主要内容,粘性将停止在那里。
这种方法的主要优点是“部分粘性”不会与“footer”或任何其他html元素在下面重叠。 它将在#container结束时停止,并且由于具有“固定”位置,当用户滚动页面时不会分散观看者的视线。
这是我能做的最好的,看起来比我发现的其他完整脚本更容易和更轻松。如果它有任何错误或者它可以进一步更新,请改进它,让我们知道。
由于jquery部分完成了,应该很容易适应其他人,只需将css文件属性更改为您的口味即可。
当足够的浏览器支持它时,可以使用['position:sticky'](https://developer.mozilla.org/en-US/docs/Web/CSS/position#Sticky_positioning) – Oriol 2014-10-16 21:27:33
哇太棒了。我不知道这个位置可用。感谢您指出它。目前还不是一个可靠的选项:http://caniuse.com/#search=sticky – 2014-10-16 22:32:15