1、動畫緩衝函數javascript
/** * 動畫函數 * 任意一個元素移動到指定的目標位置 * @param {*} element 任意一個元素 * @param {*} target 目標位置(number類型) */ function animate(element, target) { // 先清理定時器 clearInterval(element.timeId); element.timeId = setInterval(function () { // 獲取移動元素當前位置 var current = my$("dv").offsetLeft; // 每次移動距離 var step = 9; step = target > current ? step : -step; // 移動後的距離 current +=step; // 判斷是否到達目標位置 if(Math.abs(target - current) > Math.abs(step)){ my$("dv").style.left = current + "px"; }else{ clearInterval(element.timeId); my$("dv").style.left = target + "px"; } }, 20); }
2、html代碼html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; position: absolute; top: 50px; left: 50px; border: 1px solid pink; } </style> </head> <body> <input type="button" value="移動到400px" id="btn" /> <input type="button" value="移動到800px" id="btn2" /> <div id="dv"></div> <script src="./js/common.js"></script> </body> </html>
3、第三方js文件---common.jsjava
// 根據id獲取元素對象 function my$(id){ return document.getElementById(id); } /** * 動畫函數 * 任意一個元素移動到指定的目標位置 * @param {*} element 任意一個元素 * @param {*} target 目標位置(number類型) */ function animate(element, target) { // 先清理定時器 clearInterval(element.timeId); element.timeId = setInterval(function () { // 獲取移動元素當前位置 var current = my$("dv").offsetLeft; // 每次移動距離 var step = 9; step = target > current ? step : -step; // 移動後的距離 current +=step; // 判斷是否到達目標位置 if(Math.abs(target - current) > Math.abs(step)){ my$("dv").style.left = current + "px"; }else{ clearInterval(element.timeId); my$("dv").style.left = target + "px"; } }, 20); }
4、效果圖函數
初始位置截圖動畫
初始位置---->400px處ui
400px處----->800px處htm
800px處----->400px處對象
5、源碼blog
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; position: absolute; top: 50px; left: 50px; border: 1px solid pink; } </style> </head> <body> <input type="button" value="移動到400px" id="btn" /> <input type="button" value="移動到800px" id="btn2" /> <div id="dv"></div> <!-- 引入第三方js文件 --> <script src="./js/common.js"></script> <script> my$("btn").onclick = function(){ animate(my$("dv"),400); } my$("btn2").onclick = function(){ animate(my$("dv"),800); } </script> </body> </html>