<head>
<meta charset="UTF-8">
<title>test</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 50px;
height: 50px;
background: red;
border: 1px solid green;
position: absolute;
left: 0;
top: 0;
}
textarea {
position: fixed;
left: 0;
top: 100px;
}
button {
position: fixed;
left: 0;
top: 300px;
width:100px;
height: 30px;
}
span {
width: 1px;
height: 100px;
border-right: 1px solid black;
position: absolute;
left: 300px;
top: 0;
}
</style>
</head>
<body>
<textarea name="" id="" cols="30" rows="10"></textarea>
<div>div1</div>
<span></span>
<button>开始运动</button>
<script src="test.js"></script>
<script>
window.onload = function() {
var oDiv1 = document.getElementsByTagName('div')[0];
var oBtn = document.getElementsByTagName('button')[0];
oBtn.onclick = function() {
move(oDiv1, 'left');
};
}
</script>
</body>
/**
* [getStyle 获取计算出来的样式]
* @param {[type]} obj [元素对象]
* @param {[type]} attr [属性名]
* @return {[type]} [对应属性名的值]
*/
function getStyle(obj, attr) {
if (obj.currentStyle) {
// IE
return obj.currentStyle[attr];
} else {
// 其他
return getComputedStyle(obj, false)[attr];
}
}
var timer = null;
function move(obj, attr) {
// 宽度动画
var speed = 38;
// 解决重复触发定时器
clearInterval(timer);
timer = setInterval(function() {
// 是否到达终点
// 这样判断到达终点的时候会有bug
if (parseInt(getStyle(obj, attr)) >= 300) {
clearInterval(timer);
} else {
obj.style.left = parseInt(getStyle(obj, attr)) + speed + 'px';
}
var oTextarea = document.getElementsByTagName('textarea')[0];
oTextarea.value += parseInt(getStyle(obj, attr)) + '\n';
}, 30);
}