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);
}
本站文章版權歸原作者及原出處所有 。內容為作者個人觀點, 并不代表本站贊同其觀點和對其真實性負責,本站只提供參考并不構成任何投資及應用建議。本站是一個個人學習交流的平臺,網站上部分文章為轉載,并不用于任何商業目的,我們已經盡可能的對作者和來源進行了通告,但是能力有限或疏忽,造成漏登,請及時聯系我們,我們將根據著作權人的要求,立即更正或者刪除有關內容。本站擁有對此聲明的最終解釋權。