Emi*_*sen 4 css position sidebar fixed
如何获得固定的侧边栏,如包含此网站上的社交按钮的侧边栏:
http://www.tripwiremagazine.com/2012/11/social-media-buttons-and-icon-sets.html
我希望我的侧边栏固定在我的屏幕顶部,当我向下滚动但在页面顶部必须有一个绝对位置,以便它停止跟随浏览器,因为我scrool.
目前我只是使用:
#sidebar { position:fixed; }
Run Code Online (Sandbox Code Playgroud)
但是当到达页面顶部时,这并没有给它一个绝对的位置.
谢谢
HTML
<div class="wrapper"><div class="abs" id="sidebar"></div></div>
Run Code Online (Sandbox Code Playgroud)
CSS
.abs { position: absolute; }
.fixed {
position: fixed;
top: 30px !important;}
#sidebar {
top: 150px;
left: 0;
height: 100px;
width: 20px;
background-color: #ccc;}
.wrapper {
height: 1500px;
padding: 20px;}
Run Code Online (Sandbox Code Playgroud)
jQuery的
$(document).scroll(function() {
var scrollPosition = $(document).scrollTop();
var scrollReference = 10;
if (scrollPosition >= scrollReference) {
$("#sidebar").addClass('fixed');
} else {
$("#sidebar").removeClass('fixed');
$("#sidebar").addClass('abs');
};
});
Run Code Online (Sandbox Code Playgroud)
这段代码的演示:
<div class="wrapper">
Run Code Online (Sandbox Code Playgroud)
是内容的例子.