您的位置:首页 > Web前端 > JavaScript

javascript运动框架多物体运动---1

2015-08-04 15:23 746 查看
<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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: