首页 > 代码库 > JS-DOM:基础实操---以“对联”方式固定在页面
JS-DOM:基础实操---以“对联”方式固定在页面
主要见于:天猫主页右侧的固定栏、京东主页右侧固定栏
方法一:
CSS部分:
<style type="text/css">
body{
height: 3000px;
}
#div1{
width: 50px;
height: 150px;
background-color: #ccc;
position: absolute;
right: 0;
/*top: 50%;*/
/*margin-top: -75px;*/
}
</style>
HTML部分:
<body>
<div id="div1"></div>
</body>
JS-DOM部分:
<script>
window.onload=function(){
var oDiv=document.getElementById("div1");
var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;
//获取可视区的高度
var bodyHeiht=document.documentElement.clientHeight;
var top=(bodyHeight-oDiv.offsetHeight)/2+bodyScrollTop;
oDiv.style.top=top+"px";
window.onscroll=function(){
//var bodyScrollTop=document.body.scrollTop;
//var bodyScrollTop=document.documentElement.scrollTop;
var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;
//获取可视区的高度
var bodyHeight=document.documentElement.clientHeight;
var top=(bodyHeight-oDiv.offsetHeight)/2+bodyScrollTop;
oDiv.style.top=top+"px";
}
}
</script>
方法二:
CSS部分:
<style type="text/css">
body{
height: 3000px;
}
#div1{
width: 50px;
height: 150px;
position: absolute;
right: 0;
/*top: 50%;*/
/*margin-top: -75px;*/
}
</style>
HTML部分:
<body>
<div id="div1"></div>
</body>
JS-DOM部分:
<script>
window.onload=window.onresize=window.onscroll=function(){
var oDiv=document.getElementById("div1");
var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;
var bodyHeight=document.documentElement.clientHeight;
var top=(bodyHeight-oDiv.offsetHeight)/2+bodyScrollTop;
oDiv.style.top=top+"px";
}
</script>
方法三:
CSS部分:
<style type="text/css">
body{
height: 3000px;
}
#div1{
width: 50px;
height: 150px;
position: absolute;
right: 0;
/*top: 50%;*/
/*margin-top: -75px;*/
}
</style>
HTML部分:
<body>
<div id="div1"></div>
</body>
JS-DOM部分:
<script>
window.onload=function(){
var oDiv=document.getElementById("div1");
if(window.navigator.userAgent.indexOf("MSIE 6")!=-1){
function move(){
var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;
var bodyHeight=document.documentElement.clientHeight;
var t=bodyScrollTop+(bodyHeight-oDiv.offsetHeight)/2;
oDiv.style.top=t+"px";
}
move();
window.onresize=window.onscroll=move;
}else{
oDiv.style.position="fixed";
oDiv.style.top="50%";
oDiv.style.marginTop="-75px";
}
}
</script>