這篇文章將為大家詳細講解有關JS+div如何實現勻速移動動畫與變速移動動畫,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)是一家網站制作、成都做網站,提供網頁設計,網站設計,網站制作,建網站,按需制作,網站開發(fā)公司,2013年至今是互聯(lián)行業(yè)建設者,服務者。以提升客戶品牌價值為核心業(yè)務,全程參與項目的網站策劃設計制作,前端開發(fā),后臺程序制作以及后期項目運營并提出專業(yè)建議和思路。
1.勻速移動代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> * { margin: 0; padding: 0; } div { margin-top: 20px; width: 200px; height: 100px; background-color: green; position: absolute; left: 0; top: 0; } </style> </head> <body> <input type="button" value="移動到400px" id="btn1"/> <input type="button" value="移動到800px" id="btn2"/> <div id="dv"> <script src="common.js"></script> <script> //點擊按鈕移動div my$("btn1").onclick = function () { animate(my$("dv"), 400); }; my$("btn2").onclick = function () { animate(my$("dv"), 800); }; //勻速動畫 function animate(element, target) { //清理定時器 clearInterval(element.timeId); element.timeId = setInterval(function () { //獲取元素的當前位置 var current = element.offsetLeft; //移動的步數 var step = 10; step = target > current ? step : -step; current += step; if (Math.abs(current - target) > Math.abs(step)) { element.style.left = current + "px"; } else { clearInterval(element.timeId); element.style.left = target + "px"; } }, 20); } </script> </div> </body> </html>
2.變速移動代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> * { margin: 0; padding: 0; } div { margin-top: 20px; width: 200px; height: 100px; background-color: green; position: absolute; left: 0; top: 0; } </style> </head> <body> <input type="button" value="移動到400px" id="btn1"/> <input type="button" value="移動到800px" id="btn2"/> <div id="dv"> <script src="common.js"></script> <script> //點擊按鈕移動div my$("btn1").onclick = function () { animate(my$("dv"), 400); }; my$("btn2").onclick = function () { animate(my$("dv"), 800); }; //變速動畫 function animate(element, target) { //清理定時器 clearInterval(element.timeId); element.timeId = setInterval(function () { //獲取元素的當前位置 var current = element.offsetLeft; //移動的步數 var step = (target-current)/10; step = step>0?Math.ceil(step):Math.floor(step); current += step; element.style.left = current + "px"; if(current==target) { //清理定時器 clearInterval(element.timeId); } }, 20); } </script> </div> </body> </html>
common.js
/** * 獲取指定標簽對象 * @param id 標簽的id屬性值 * @returns {Element}根據id屬性值返回指定標簽對象 */ function my$(id) { return document.getElementById(id); }
關于“JS+div如何實現勻速移動動畫與變速移動動畫”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
網頁題目:JS+div如何實現勻速移動動畫與變速移動動畫
轉載來源:http://aaarwkj.com/article30/jjgiso.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供虛擬主機、網站維護、ChatGPT、商城網站、小程序開發(fā)、網站改版
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)