效果:
思路:
首先,加載onscroll控制滾動條。然后寫緩存運動的方法,緩沖運動的方法是先計算出DIV緩沖的速度,并且將其取整,再進行運動判斷什么時候到達終點。最后將其參數返回。再在onscroll里面調用此方法,并且將終點計算出來賦予此方法的參數。
代碼:
復制代碼 代碼如下:
<head runat="server">
<title></title>
<style type="text/css">
#div1
{
width: 200px;
height: 200px;
background: #0000FF;
position: absolute;
right: 0;
bottom: 0;
}
</style>
<script type="text/javascript">
window.onscroll = function () {
var oDiv = document.getElementById('div1');
var DivScroll = document.documentElement.scrollTop || document.body.scrollTop; //獲取移動高度
// oDiv.style.top = (document.documentElement.clientHeight - oDiv.offsetHeight)/2 + DivScroll + 'px';
move(parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + DivScroll)); //調用傳參,其中里面的參數是DIV要走的終點。也就是(可視高度-DIV高度)/2+移動高度
};
var timer = null;
function move(end) {
clearInterval(timer); //首先,先關閉之前如果有開啟的setInterval;
timer = setInterval(function () {
var oDiv = document.getElementById('div1');
var speed = (end - oDiv.offsetTop) / 5; //計算DIV要走的速度,DIV要走的速度就等于(終點-offsetTop高度)/縮放系數
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //為了避免小數,將其取整
if (oDiv.offsetTop == end) { //當DIV到達終點,則關閉setInterval;
clearInterval(timer);
}
else {
oDiv.style.top = oDiv.offsetTop + speed + 'px'; //移動div
}
}, 30);
}
</script>
</head>
<body>
<div>
</div>
</body>
新聞熱點
疑難解答
圖片精選