fixed应用
今天在逛人人网时,发现人人网首页左侧的“应用动态”,随着我页面向下滚动,一直固定在网站的左侧。但这效果存在一点瑕疵,在拖动过程中存在一点抖动(ie下),不是非常平滑。我尝试使用jquey实现了该效果,也解决了抖动的问题。现在把它拿出来和大家分享一下。
?
人人网效果:

?
?
?
思路:
- 创建一个ID为sideBar的div,将它的position设置为absolute。当页面滚动条的垂直高度超过sideBar的top时,就将它的position设置为fixed。当页面滚动条的垂直高度小于sideBar的top时,将它的position重新设置为 absolute。sideBar要跟网页顶部保持一定距离,所以我们将sideBar的css里设置 “margin-top”(这就是发生抖动的原因)。
Ie6问题:
Ie6不支持fixed属性,所以这效果需要过滤IE6
?
//判断是否为IE6var msie6 = $.browser == 'msie' && $.browser.version < 7;//浏览器不为ie6if (!msie6) {//效果代码}?Css编写:
*{margin: 0px;padding: 0px;}body{text-align: center;}#wrapper{height: 2000px;position: relative;}#sideBar{width: 100px;height: 300px;position: absolute;top: 0px;left: 100px;background: #999;margin-top: 20px;/*与顶部的距离*/}/*不要写成.fixed ,sideBar 已经设置了position为absolute,.fixed与sideBar原有css属性同级别的,将无法覆盖原有属性。而sideBar.fixed选择的优先级别较高*/#sideBar.fixed{position: fixed;top: 0px;}#content{padding-left: 300px;padding-top: 200px;}#sideWrapper{position: absolute;width:280px;top: 100px;}?防止抖动:
动态应用与网页顶部的高度为sideBar.offset().top
为了避免抖动,我们应该在动应用距离网页窗口还有动态应用设定的magintop
的距离时,将动态应该的position?设置为fixed.
$sideBar.offset().top- parseFloat($sideBar.css("marginTop")?完整的jquery代码:
$(function() {var $sideBar = $("#sideBar"); //左侧栏与顶部的高度var top = $sideBar.offset().top - parseFloat($sideBar.css("marginTop").replace(/auto/,0));var msie6 = $.browser == 'msie' && $.browser.version < 7; if (!msie6) {$(window).scroll(//页面滚动条滚动式触发效果function() {var scrollTop = $(this).scrollTop();//拖动的高度if(scrollTop > top) {$sideBar.addClass("fixed");}else{$sideBar.removeClass("fixed");}});}});?
代码下载地址:https://github.com/yeahzan/fixed.git
原文地址:http://www.yeahzan.com/blog/item/fixed.html
?
?
?