<head>
<meta charset="UTF-8">
<title>test</title>
<style>
* {
margin: 0;
padding: 0;
}
textarea {
position: fixed;
right: 0;
top: 50px;
}
div {
margin-top: 10px;
width: 100px;
height: 30px;
background: red;
border: 1px solid green;
cursor: pointer;
}
</style>
</head>
<body style="height:3000px;">
<textarea name="" id="" cols="30" rows="10"></textarea>
<div>div1</div>
<div>div2</div>
<div>div3</div>
<script src="test.js"></script>
<script>
window.onload = function() {
var oDiv1 = document.getElementsByTagName('div');
for (var i = 0; i < oDiv1.length; i++) {
// 给每个元素对象设置一个定时器
// 用来结局定时器公用的问题
oDiv1.timer = null;
oDiv1[i].onmouseover = function() {
move(this, 400);
};
oDiv1[i].onmouseout = function() {
move(this, 100);
};
}
}
</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];
}
}
function move(obj, target) {
// 多物体运动,解决公用定时器的问题
// 不仅仅是定时器,多物体运动所有东西都不能公用
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var width = parseInt(getStyle(obj, 'width'));
var speed = (target - width) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (width == target) {
clearInterval(obj.timer);
} else {
obj.style.width = width + speed + 'px';
}
document.getElementsByTagName('textarea')[0].value += parseInt(getStyle(obj, 'width')) + '\n';
}, 30);
}
javascript运动框架多物体运动---1
最新推荐文章于 2019-02-17 20:22:07 发布