JavaScript 图片在规定时间内消失

来源:互联网 发布:联想关闭网络启动 编辑:程序博客网 时间:2024/05/12 05:06
<!DOCTYPE html><html><head><title>运动效果</title><meta charset="utf-8" /></head><style>div {width: 200px;height: 200px;background: red;opacity: 1;}</style><script>window.onload = function(){//获取DIV的相关内容var oDiv = document.getElementsByTagName('div')[0];//设置鼠标点击事件oDiv.onclick = function (){//1秒内使得oDiv对象的opacity属性的值变成0simpleAnimation(this,'opacity',0,1000);}function simpleAnimation (obj,attr,target,time){//获取刚开始的属性var start = parseFloat(getStyle(obj,attr));//计算变化量var delta = target - start;//计算变化的总次数(向上取整)var total = Math.ceil(time / 30);//记录当前变化是第几次变化//如果当前变化已经是最后一次,那么//就要使得变化直接变成最终结果var count = 0;var timer = setInterval(function(){var unit = 'px';//当属性值为opacity透明度的时候,我们是不需要px的if (attr == 'opacity'){unit = '';}//变化次数+1count++;//如果已经是最后一次变化了if (count == total) {obj.style[attr] = target + unit;clearInterval(timer);timer = null;} else {obj.style[attr] = start + delta*count/total + unit;}},30);}//获取某个对象的某个属性function getStyle(obj,attr){if(typeof(obj.currentStyle) == 'undefined'){return getComputedStyle(obj,null)[attr];} return obj.currentStyle[attr];}}</script><body><div></div></body></html>

0 0