在web端迂求,側(cè)邊欄經(jīng)常會出現(xiàn),代碼展示如何實現(xiàn)側(cè)邊欄的定位
實現(xiàn)側(cè)邊欄定位最簡單的就是使用固定定位晃跺,但是固定定位在ie6中不支持
在ie6中只能使用代碼中展示的js去計算定位
在其他瀏覽器中揩局,可以使用代碼中樣式注釋掉的方式進行定位,很方便
<!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;
* 使用固定定位可以實現(xiàn)側(cè)邊欄定位凌盯,完全不需要js;但是在ie6中不支持固定定位*/
}
</style>
<script>
//window.onresize 處理在窗口放大縮小時烹玉,側(cè)邊欄的位置
//window.onload 處理在窗口加載時驰怎,側(cè)邊欄的位置
//window.onscroll 處理在窗口滾動時,側(cè)邊欄的位置
window.onresize = window.onload = window.onscroll = function(){
var oDiv = document.getElementById("div1");
//在不同的瀏覽器中一下document.documentElement.scrollTop二打,document.body.scrollTop 這兩個值總會有一個恒為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>
以上代碼實現(xiàn)县忌,不管是放大縮小窗口還是滾動窗口都能實現(xiàn)側(cè)邊欄的定位