固定位置侧栏兼容代码

有时候为了提高用户体验,或者其他目的,需要使侧栏固定。

如果不考虑兼容ie 6那么就很简单:

#sidenav {
width: 300px;
position: fixed; /*–Fix the sidenav to stay in one spot–*/
float: left; /*–Keeps sidenav into place when Fixed positioning fails–*/
}

sidenav 的父div需要position: relative; 就ok了。

如果想要全面兼容那么就稍微复杂点,加css:

/* Unfortunately the fixed position property is not supported in IE6 */
*html #sidenav {
position: absolute;
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + ‘px’ );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + ‘px’ );
}

js:

$(document).ready(function() {

function staticNav() {
var sidenavHeight = $(“#sidenav”).height();
var winHeight = $(window).height();
var browserIE6 = (navigator.userAgent.indexOf(“MSIE 6”)>=0) ? true : false;

if (browserIE6) {
$(“#sidenav”).css({‘position’ : ‘absolute’});
} else {
$(“#sidenav”).css({‘position’ : ‘fixed’});
}

if (sidenavHeight > winHeight) {
$(“#sidenav”).css({‘position’ : ‘static’});
}
}

staticNav();

$(window).resize(function () { //Each time the viewport is adjusted/resized, execute the function
staticNav();
});

});

然后还要引用jquery。这样就ok了

推荐个不错的CSS博客: http://ilikecss.com/blog/fixed-sidenav-layout/

发表评论