JavaScript緩衝運動實現方法(2則樣本)_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了JavaScript緩衝運動實現方法。分享給大家供大家參考,具體如下:

實現原理:(目標距離-當前距離) / 基數 = 速度(運動距離越大速度越小,運動距離和速度成反比)

複製代碼 代碼如下:
(500 - oDiv.offsetLeft) / 7 = iSpeed;

需要注意:當計算出來的速度有小數時需要取整;

複製代碼 代碼如下:
(500 - oDiv.offsetLeft) / 7 = iSpeed; iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);

例子1:滑塊緩衝運動

<!doctype html><html><head><meta charset="utf-8"><title>緩衝運動</title><style>#div1{ width:100px; height:100px; background:red; position:absolute; top:50px; left:0;}span{ width:1px; height:300px; background:black; position:absolute; left:300px; top:0; display:block;}</style><script>window.onload = function(){ var oBtn = document.getElementById('btn1'); var oDiv = document.getElementById('div1'); oBtn.onclick = function() {  startMove(oDiv, 300); };};var timer = null;function startMove(obj, iTarget){ clearInterval(timer); timer = setInterval(function(){  var iSpeed = (iTarget - obj.offsetLeft)/8;  iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);  if(iTarget==obj.offsetLeft){   clearInterval(timer);  }else{   obj.style.left = obj.offsetLeft + iSpeed + 'px';  } }, 30);}</script></head><body><input id="btn1" type="button" value="移動" /><div id="div1"></div><span></span></body></html>

例子2:側邊欄滑動

<!doctype html><html><head><meta charset="utf-8"><title>側邊欄滑動</title><style>#div1{ width:100px; height:100px; background:red; position:absolute; right:0; top:0;}</style><script>window.onload = window.onscroll = function(){ var oDiv = document.getElementById('div1'); var iScrollTop = document.documentElement.scrollTop || document.body.scrollTop; var clientHeight = document.documentElement.clientHeight; var iH = (clientHeight - oDiv.offsetHeight)/2 + iScrollTop; //oDiv.style.top = iH + 'px'; startMove(oDiv, parseInt(iH));};var timer = null;function startMove(obj, iTarget){ clearInterval(timer); timer = setInterval(function(){  var iSpeed = (iTarget - obj.offsetTop) / 8;  iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);  if(obj.offsetTop == iTarget){   clearInterval(timer);  }else{   obj.style.top = obj.offsetTop + iSpeed + 'px';  } }, 30);}</script></head><body style="height:2000px;"><div id="div1"></div></body></html>

更多關於JavaScript運動效果相關內容可查看本站專題:《JavaScript運動效果與技巧匯總》

希望本文所述對大家JavaScript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.