タイマーはdivの動きを制御し、簡単なアニメーションを実行できる関数を作成します
1.指定した要素の現在のスタイルを取得する関数を定義します
* 定义一个函数,用来获取指定元素的当前的样式
* 参数:
* obj 要获取样式的元素
* name 要获取的样式名
*/
function getStyle(obj , name){
if(window.getComputedStyle){
return getComputedStyle(obj , null)[name];
}else{
return obj.currentStyle[name];
}
}
2.簡単なアニメーションを実行できる関数を作成します
function move(obj, attr, target, speed, callback) {
clearInterval(obj.timer);
var current = parseInt(getStyle(obj, attr));
if(current > target) {
speed = -speed;
}
obj.timer = setInterval(function() {
var oldValue = parseInt(getStyle(obj, attr));
var newValue = oldValue + speed;
if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)) {
newValue = target;
}
obj.style[attr] = newValue + "px";
if(newValue == target) {
clearInterval(obj.timer);
callback && callback();
}
}, 30);
}
3.コード
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
var btn02 = document.getElementById("btn02");
btn01.onclick = function(){
move(box1 , 800 , 10);
};
btn02.onclick = function(){
move(box1 , 0 , 10);
};
};
var timer;
function move(obj , target ,speed){
clearInterval(timer);
var current = parseInt(getStyle(obj,"left"));
if(current > target){
speed = -speed;
}
timer = setInterval(function(){
var oldValue = parseInt(getStyle(obj,"left"));
var newValue = oldValue + speed;
if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)){
newValue = target;
}
obj.style.left = newValue + "px";
if(newValue == target){
clearInterval(timer);
}
},30);
}
function getStyle(obj , name){
if(window.getComputedStyle){
return getComputedStyle(obj , null)[name];
}else{
return obj.currentStyle[name];
}
}
</script>
</head>
<body>
<button id="btn01">点击按钮以后box1向右移动</button>
<button id="btn02">点击按钮以后box1向左移动</button>
<br /><br />
<div id="box1"></div>
<div style="width: 0; height: 1000px; border-left:1px black solid; position: absolute; left: 800px;top:0;"></div>
</body>
</html>