給一個原先的電子商務網站做修改,客戶說想將原先上下滑動側邊欄改的更加人性化,希望將原先勻速滑動的側邊欄改成變速運動的側邊欄,在到達目的地之前速度越變越慢。
原先一開始的時候,,這個圖片是硬生生地到達可視區的中點,看得有點愣愣傻傻的。
原先的代碼是這樣:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #testDiv1 { width:225px;height:97px;position:absolute; right:0} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>上下滑動側邊欄</title> <script type="text/javascript"> window.onload = window.onscroll = function () { var sDiv = document.getElementById('testDiv1'); // document.body.scrollTop 兼容谷歌瀏覽器 // document.documentElement.scrollTop 兼容IE瀏覽器 //滾動點離瀏覽器頂部的距離 var varTop = document.documentElement.scrollTop || document.body.scrollTop; //給DIV的高賦值 sDiv.style.top = varTop + (document.documentElement.clientHeight - sDiv.offsetHeight) / 2 + 'px'; } </script> </head> <body style="height:2000px;"> <div id="testDiv1"><img src="kf.jpg" alt="" /></div> </body> </html>
只是讓div立馬居中。
要讓div在到達終點前,變速地運動到終點,而且速度越來越慢,就得讓sDiv.style.top的值的變化率一點一點地變慢。
於是增加了代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #testDiv1 { width:225px;height:97px;position:absolute; right:0} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>上下滑動側邊欄</title> <script type="text/javascript"> window.onload = window.onscroll = function () { var sDiv = document.getElementById('testDiv1'); // document.body.scrollTop 兼容谷歌瀏覽器 // document.documentElement.scrollTop 兼容IE瀏覽器 //滾動點離瀏覽器頂部的距離 var varTop=document.documentElement.scrollTop||document.body.scrollTop; //oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+'px'; var t = varTop + (document.documentElement.clientHeight - sDiv.offsetHeight) / 2; //給DIV的高賦值 //document.documentElement.clientHeight可見區域的高度 //oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+'px'; //讓速度發生變化 startMove(parseInt(t),7); } var varTimer = null; function startMove(destination,speed) { var sDiv = document.getElementById('testDiv1'); //開啟一個定時器 clearInterval(varTimer); varTimer = setInterval(function () { //div一開始離目標的距離除以speed div移動的速度 div距離越近 速度越小 var varSpeed = (destination - sDiv.offsetTop) / speed; //Round是四舍五入 ceil向上取整。。floor向下取整 varSpeed = varSpeed > 0 ? Math.ceil(varSpeed) : Math.floor(varSpeed); //到達目的地 清除定時器 if (sDiv.offsetTop == destination) { clearInterval(varTimer); } else { //移動 sDiv.style.top = sDiv.offsetTop + varSpeed + 'px'; } }, 30); } </script> </head> <body style="height:3000px;"> <div id="testDiv1"><img src="kf.jpg" alt="" /></div> </body> </html>