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

javascript运动基础——多个物体同时运动

2018-03-05 13:47 337 查看

<!DOCTYPE HTML>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {
width: 100px;
height: 200px;
background: red;
position: absolute;
left: -100px;
top: 100px;
}

#div2 {
width: 30px;
height: 60px;
background: black;
position: absolute;
right: -30px;
top: 70px;
color: white;
text-align: center;
}

#w {
opacity: 0.3;
filter: alpha(opacity=30);
margin-left: 200px;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<script>
window.onload = function() {

var oDiv1 = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
var oImg = document.getElementById('w');
//var iTimer = null;

oDiv1.onmouseover = function() {
startMove(this, 'left', 0, 10);
}

oDiv1.onmouseout = function() {
startMove(this, 'left', -100, -10);
}

oImg.onmouseover = function() {
startMove(this, 'opacity', 100, 10);
}

oImg.onmouseout = function() {
startMove(this, 'opacity', 30, -10);
}

function startMove(obj, attr, iTarget, iSpeed) {
clearInterval(obj.iTimer);
var iCur = 0;

obj.iTimer = setInterval(function() {

if(attr == 'opacity') {
iCur = Math.round(css(obj, 'opacity') * 100);
} else {
iCur = parseInt(css(obj, attr));
}

if(iCur == iTarget) {
clearInterval(obj.iTimer);
} else {
if(attr == 'opacity') {
obj.style.opacity = (iCur + iSpeed) / 100;
obj.style.filter = 'alpha(opacity=' + (iCur + iSpeed) + ')';
} else {
obj.style[attr] = iCur + iSpeed + 'px';
}
}

}, 30);
}

function css(obj, attr) {
//IE不支持getComputedStyle,它有自己的一个实现方式,那就是currentStyle
if(obj.currentStyle) {
return obj.currentStyle[attr];
} else {
//getComputedStyle用来获取属性
return getComputedStyle(obj, false)[attr];
}
}

}
</script>
</head>

<body>
<div id="div1">
<div id="div2">分享到</div>
</div>

<div id="w"></div>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: