本篇博客的技术点关键在于解析json数组、动画原理、函数的封装思想和获取元素的属性等方面也是比较综合的一个案例了。学习一下对于知识点的整合很有必要。
下面贴出html的相关代码如下。注释非常详细,相信机智的你一眼就能看懂。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>仿360开机小助手</title>
<style type="text/css">
.box {
width: 322px;
position: fixed;
bottom: 0;
right: 0;
}
span {
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box" class="box">
<span></span>
<div class="hd" id="t">
<img src="images/t.jpg" />
</div>
<div class="bd" id="b">
<img src="images/b.jpg" />
</div>
</div>
</body>
</html>
<script>
function $(id){return document.getElementById(id);}
var b = document.getElementById("b");
var span = document.getElementsByTagName("span")[0];
span.onclick = function(){
animate(b,{height:0},function(){
animate(b.parentNode,{width:0})
});
}
// 谁的 哪个属性 函数回调
function animate(obj,json,fn){
// 1.清除定时器
clearInterval(obj.timer);
// 2.设置定时器
obj.timer = setInterval(function(){
// 3.关闭定时器标志位
var flag = true;
// 4.遍历json数组
for(var attr in json){
// 5.计算当前属性值
var current = 0;
current = parseInt(getStyle(obj,attr));
// 6.计算步长
var step = (json[attr] -current)/10;
step = step >0 ? Math.ceil(step):Math.floor(step);
// 7.代入动画公式
obj.style[attr] = current + step + "px";
if(current != json[attr]){
flag = false;
}
}
if(flag){
clearInterval(obj.timer);
if(fn){
fn();
}
}
},30);
}
// 谁的 哪个属性
function getStyle(obj,attr){
if(obj.currentStyle){
// ie6
return obj.currentStyle[attr];
}else{
// 标准浏览器
return window.getComputedStyle(obj,null)[attr];
}
}
</script>