在web端,側(cè)邊欄經(jīng)常會(huì)出現(xiàn),代碼展示如何實(shí)現(xiàn)側(cè)邊欄的定位
實(shí)現(xiàn)側(cè)邊欄定位最簡(jiǎn)單的就是使用固定定位,但是固定定位在ie6中不支持
在ie6中只能使用代碼中展示的js去計(jì)算定位
在其他瀏覽器中,可以使用代碼中樣式注釋掉的方式進(jìn)行定位,很方便
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
right: 0;
/*position: fixed;
* top:50%;
* margin-top:-50px;
* 使用固定定位可以實(shí)現(xiàn)側(cè)邊欄定位,完全不需要js;但是在ie6中不支持固定定位*/
}
</style>
<script>
//window.onresize 處理在窗口放大縮小時(shí),側(cè)邊欄的位置
//window.onload 處理在窗口加載時(shí),側(cè)邊欄的位置
//window.onscroll 處理在窗口滾動(dòng)時(shí),側(cè)邊欄的位置
window.onresize = window.onload = window.onscroll = function(){
var oDiv = document.getElementById("div1");
//在不同的瀏覽器中一下document.documentElement.scrollTop,document.body.scrollTop 這兩個(gè)值總會(huì)有一個(gè)恒為0
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
var t = (document.documentElement.clientHeight - oDiv.offsetHeight)/2;
oDiv.style.top = scrollTop + t + "px";
}
</script>
</head>
<body style="height: 2000px;">
<div id="div1"></div>
</body>
</html>
以上代碼實(shí)現(xiàn),不管是放大縮小窗口還是滾動(dòng)窗口都能實(shí)現(xiàn)側(cè)邊欄的定位