学习视频资源来自慕课网《js动画效果》:http://www.imooc.com/learn/167
所谓同时运动——多个动画同时进行,eg: 同时发生变宽和变高的运动效果。学习到这里,已经是本课程的最后一节了,收获颇丰啊!废话少说,我还是把这节学到的东西归纳如下:
实现几个运动效果同时运行的关键点:将属性名和属性值封装在JSON对象中,通过参数传给处理函数,当然playFun函数需要改写。
playFun函数改写注意点:
1)json值的遍历及取值
for(var item in json){
//取值
json[item]
}
2)多动画同时运动,需要确定所有动画都运行到达目标值,完整的运动才算完成,实现方法:
老师提供的方法:设标志做判断,定时器一开始时,设置flag = true 假设运动全部完整运行完成,此时才能clearInterval(timer) 并调用回调函数;否则 修改 flag = false,运动继续进行。
实现代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
*{
padding:0;
margin:0;
}
ul li{
list-style:none;
width:200px;
height:100px;
background:green;
margin:20px;
border:2px #ccc solid;
filter:alpha(opacity:30);
opacity:0.3;
}
</style>
<script type="text/javascript">
/****
实现几个运动效果同时运行的关键点:
将属性名和属性值封装在JSON对象中,通过参数传给处理函数,当然playFun函数需要改写。
playFun函数改写注意点:
1)json值的遍历及取值
for(var item in json){
//取值
json[item]
}
2)多动画同时运动,需要确定所有动画都运行到达目标值,完整的运动才算完成
设标志做判断,老师提供的方法:定时器一开始时,设置flag = true 假设运动全部完整运行完成,
此时才能clearInterval(timer) 并调用回调函数;否则 修改 flag = false,运动继续进行。
***/
window.onload = function(){
var testLi = document.getElementById("testLi");
testLi.onmouseover = function(){
playFun(testLi,{width:"300", height:"300", opacity:"100"},function(){
alert("hello");
});
};
testLi.onmouseout = function(){
playFun(testLi,{width:"200", height:"100", opacity:"30"},function(){
alert("test succuss");
});
}
function playFun(obj,json,fn){//fn——回调函数
clearInterval(obj.timer);
obj.timer = setInterval(function(){
//flag = true用于假设多个运动效果都已运行结束
var flag = true;
for(var item in json){
var itarget = json[item];
var getValue = 0;
if(item == "opacity"){
getValue = Math.round(parseFloat(getStle(obj,item))*100);
}else{
getValue = parseInt(getStle(obj,item));
}
var speed = (itarget - getValue)/10;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
//判断只要有某运动未结束,则继续进行
if(getValue != itarget){
flag = false;
if(item == "opacity"){
getValue += speed;
obj.style["filter"] = "alpha(opacity:"+ getValue +")";
obj.style["opacity"] = getValue/100;
}else{
obj.style[item] = getValue + speed + "px";
}
}
}
//如果所有运动都已达到目标值,则物体才停止运动
if(flag == true){
clearInterval(obj.timer);
if(fn){ //动画结束后判断是否调用回调函数,存在即执行
fn();
}
}
},50);
}
//获取属性值
function getStle(ele,attr){
if(ele.currentStyle){ //兼容IE浏览器
return ele.currentStyle[attr];
}else{ //兼容firefox浏览器
return getComputedStyle(ele,false)[attr];
}
}
}
</script>
</head>
<body>
<ul>
<li id="testLi"></li>
</ul>
</body>
</html>