```html
<!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"></div>
<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;
// Math.ceil是四舍五入,Math.floor是去下界
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current += step;
element.style.left = current + "px";
if(current == target) {
//清理定時器
clearInterval(element.timeId);
}
//測試代碼:
console.log("目標位置:"+target+",當前位置:"+current+",每次移動步數:"+step);
}, 20);
}
</script>
</body>
</html>
```
- js應用場景
- js組成
- js書寫位置
- 浮點數精度問題
- undefined與null的區別
- 數據類型轉換
- 運算符優先級
- 代碼調試
- 函數
- 函數的定義和調用
- 函數的return細節
- 函數是一種數據類型
- this的指向
- 函數成員
- 函數閉包
- 作用域
- 預解析
- js對象
- 對象的創建與調用
- new關鍵字
- this關鍵字
- 構造函數創建對象
- 事件
- 數據類型
- 繼承
- 雜項
- 如何阻止標簽的默認行為
- 為一個標簽綁定或移除任何一個事件
- 如何阻止事件的冒泡行為
- 事件的三個階段
- 移動元素的條件
- 勻速動畫函數封裝
- 變速動畫函數封裝
- 獲取元素的css屬性值
- 數據類型判斷方法
- 創建對象的7種寫法
- 如何繼承
- 為js內置對象添加原型函數
- 將局部變量轉換為全局變量
- call函數的用法
- 沙箱
- 淺拷貝
- 深拷貝
- 對象賦值會改變對象
- 解析URL中的字符串
- 格式化日期
- 獲取當前瀏覽器類型
- Vue3.x
- 調式工具Vue Devtools