JS实现动画

实现的效果:当鼠标移动到目标图片时,图片会不断变宽高和透明度,当变化到目标值以后停止;当鼠标移开后,图片做相反的动画(变窄变矮…)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Animation</title>
    <style type="text/css">
    body{
        margin: 0px;
        padding: 0px;
        font-size: 14px;
    }
    #block{
        float: left;
        width: 200px;
        height: 200px;
        background-image: url(img.jpg);
        filter:alpha(opacity:100);
        opacity: 1;
    }
    </style>

    <script type="text/javascript">
    window.onload=function(){
        var obj = document.getElementById("block");
        obj.onmouseover=function(){
            startAnim(obj,{"height":400,"width":400,"opacity":30});
        }
        obj.onmouseout=function(){
            startAnim(obj,{"height":200,"width":200,"opacity":100});
        }
    }

    function startAnim(obj,json,fn){
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var flag = true;
            for(var attr in json){
                var curr = 0;
                if(attr=="opacity"){
                    curr = Math.round(parseFloat(getStyle(obj,attr)*100));
                }else{
                    curr = parseInt(getStyle(obj,attr));
                }

                obj.speed = (json[attr]-curr)/10; 
                obj.speed = obj.speed>0?Math.ceil(obj.speed):Math.floor(obj.speed);
                if(curr!=json[attr]){
                    flag = false;
                }

                if(attr=="opacity"){
                    obj.style.filter="filter:alpha(opacity:"+(obj.speed+curr)+");"
                    obj.style.opacity=(obj.speed+curr)/100;
                }else{
                    obj.style[attr] = curr+obj.speed+"px";
                }
            }

            if(flag){
                clearInterval(obj.timer);
                // alert("hahha");
                if(fn){
                    fn();
                }
            }

        },30);
    }

    /*
      style 只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。
      currentStyle 可以弥补style的不足,但是只适用于IE。
      getComputedStyle 同currentStyle作用相同,但是适用于FF、opera、safari、chrome
    */
    function getStyle(obj,attr){
        if(obj.currentStyle){
            return obj.currentStyle[attr];
        }else{
            return getComputedStyle(obj,null)[attr];
        }
    }
    </script>

</head>
<body>
    <h2 align="center">Animation</h2>
    <hr>
    <div id="block"></div>
</body>
</html>

该框架可以在以后的开发中复用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值