为什么透明动画没有结果!

来源:4-4 任意属性值(二)

记得喝水

2015-12-07 09:56

<!DOCTYPE HTML>
<html lang="en/zh">
<head>
    <meta charset="UTF-8">
    <title>JS_动画任意属性值一</title>
    <style type="text/css">
        *{
            padding: 0px;
            margin: 0px;            
        }
        #div1{
            width: 200px;
            height: 200px;
            background: red;
            border: 2px solid blue;    
            filter:alpha(opacity:30);    /*ie低版本不支持opacity的  只支持filter */    
            opacity: 0.3;    /*firefox,chrome*/
        }
    </style>
    <script type="text/javascript">
        window.onload=function(){            
            var div1=document.getElementById("div1");
            div1.onmouseover=function(){
                move(this,"opacity",100);
            }
            div1.onmouseout=function(){
                move(this,"opacity",30);
            }
        }

        /*动画函数*/
        var timer=null;
        var speed=0;        
        function move(obj,attr,target){
            clearInterval(obj.timer);
            obj.timer=setInterval(function(){
                var speed=0;    
                var cur=0;
                if (attr=="opacity") {
                    cur=Math.round(parseFloat(getStyle(obj.attr))*100);
                }else{
                    var cur=parseInt(getStyle(obj,attr));
                }                
                var speed=(target-cur)/8;
                speed=speed>0?Math.ceil(speed):Math.floor(speed);
                if(cur==target){
                    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);
        }
        /*获取样式函数*/
        function getStyle(obj,attr){
            if (obj.currentStyle) {
                return obj.currentStyle[attr];
            }else{
                return getComputedStyle(obj,false)[attr];
            }
        }
    </script>
</head>
<body>
    <div id="div1"></div>
</body>
</html>


写回答 关注

2回答

  • 一毛钱
    2015-12-07 10:00:41
    已采纳
     if (attr=="opacity") {
                        cur=Math.round(parseFloat(getStyle(obj.attr))*100);
                    }else{
                        var cur=parseInt(getStyle(obj,attr));
                    }

    太马虎了吧逗号写成了点,应该是这样的 cur=Math.round(parseFloat(getStyle(obj,attr))*100);

  • 木子舟义
    2015-12-07 10:02:49

    虽然我知道为什么,问人问题 用这个态度是不是不太恰当。

    记得喝水

    嗯,是,当时太着急了。不好意思啊!大侠:)

    2015-12-07 10:24:55

    共 1 条回复 >

JS动画效果

通过本课程JS动画的学习,从简单动画开始,逐步深入各种动画框架封装

113925 学习 · 1443 问题

查看课程

相似问题