JS简单的多物体运动框架
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div{
width: 100px;
height: 50px;
background: red;
margin: 10px;
}
</style>
<script>
window.onload = function(){
aDiv = document.getElementsByTagName('div');
for (var i = 0;i<aDiv.length;i++) {
aDiv[i].timer = null;
aDiv[i].onmouseover = function(){
starMove(this,500);
}
aDiv[i].onmouseout = function(){
starMove(this,100);
}
}
}
function starMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (iTarget-obj.offsetWidth)/6;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth==iTarget)
{
clearInterval(obj.timer);
}else
{
obj.style.width = obj.offsetWidth+speed+'px';
}
},30)
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
多物体实现淡入淡出
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div{
height: 100px;
width: 100px;
margin: 20px;
float: left;
background: red;
filter: alpha(opacity:30);
opacity: 0.3;
}
</style>
<script type="text/javascript">
window.onload = function(){
var aDiv = document.getElementsByTagName('div');
for (var i = 0;i<aDiv.length;i++) {
aDiv[i].alpha = 30;
aDiv[i].timer = null;
aDiv[i].onmouseover = function(){
starMove(this,100);
}
aDiv[i].onmouseout = function(){
starMove(this,30);
}
}
}
function starMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (iTarget-obj.alpha)/6;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.alpha == iTarget)
{
clearInterval(obj.timer);
}else
{
obj.alpha+=speed;
//赋值
obj.style.filter = 'alpha(opacity:'+obj.alpha+')';
obj.style.opacity = obj.alpha/100;
}
},30)
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
运动框架的bug修复和改善
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 200px;
height: 200px;
background: red;
border: 1px solid black;
opacity: 0.3;
}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
//定义为自己的属性,是为了多运动框架
oDiv.timer = null;
oDiv.onmouseover = function(){
starMove(this,'opacity',100);
}
oDiv.onmouseout = function(){
starMove(this,'opacity',30);
}
}
//获取属性
function getStyle(obj,name)
{
if(obj.currentStyle)
{
return obj.currentStyle[name];
}else
{
return getComputedStyle(obj,true)[name];
}
}
//运动框架,可以兼容尺寸属性变化和透明度
function starMove(obj,attr,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var cur = 0;
if(attr=='opacity')
{
cur = Math.round(parseFloat(getStyle(obj,attr))*100);
}else
{
cur =parseInt(getStyle(obj,attr));
}
var speed = (iTarget-cur)/6;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(cur==iTarget)
{
clearInterval(obj.timer);
}else
{
if(attr=='opacity')
{
obj.style.filter = 'alpha(opacity:'+cur+speed+');'
obj.style.opacity = (cur+speed)/100;
}else
{
obj.style[attr] = cur+speed +'px';
}
}
},30)
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>