示例:屏幕右侧悬浮框
原理:oDiv.style.top = document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop + "px";
知识点:
浏览器窗体的高度
document.documentElement.clientHeight
浏览器滚动的高度
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
html部分
<body style=" height:1600px;"> <div id="div1"></div> </body> #div1 { position:absolute; right:0; bottom:0; width:100px; height:150px; background:green;}
js部分
<script> window.onscroll = function(){ var oDiv = document.getElementById("div1"); var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; //oDiv.style.top = document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop + "px"; oDiv.style.top = startMove(document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop); } var timer = null; function startMove(iTarget){ clearInterval(timer); timer = setInterval(function(){ var oDiv = document.getElementById("div1"); var speed = (iTarget - oDiv.offsetTop)/4; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if(oDiv.offsetTop == iTarget){ clearInterval(timer); } else { oDiv.style.top = oDiv.offsetTop + speed + "px"; } },30); } </script>