码迷,mamicode.com
首页 > 其他好文 > 详细

2016-06-01 抖动

时间:2016-06-01 22:40:56      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

1.点击图片实现抖动技术分享

    <script src="js/domoveandgetstyle.js"></script>
    <script>
        window.onload=function(){
            var img = document.getElementById("img");
            var arr=[];//20 -20 18 -18 ...0
            var num=0;//操作数组,一般要用到的下标
            var timer=null;//取消定时器用
            var postion=getStyle(img,‘left‘);//获取img的当前位置
            for(var i=20; i>0; i-=2){
                arr.push(i,-i);
            }
            //alert(arr)//20 -20 18 -18 ...0
            img.onclick=function(){//点击图片触发定时器
                timer=setInterval(function(){
                    img.style.left=postion+arr[num]+‘px‘;
                    num++;
                    if(num==arr.length){//如果到数组的末尾,清除定时器
                        clearInterval(timer);
                    }
                },50);
            }
        }
    </script>
</head>
<body>
<img id="img" src="images/photo_04.jpg" style="width: 400px ; height: 400px;position:absolute;left: 300px" />
</body>

 2. domoveandgetstyle.js 

/**
 * Created by ckang on 2016/6/1.
 */
function doMove(obj,attr,stepLength,target,animationVelocity){
    stepLength=(getStyle(obj,attr)<target?stepLength:-stepLength);//如果obj所处的位置小于目标位置,则步长取正数,反之取负数
    clearInterval(obj.timer);
    odiv.timer=setInterval(function(){
        var speed =getStyle(obj,attr)+stepLength;//步长
        if(speed>target && stepLength>0 || speed<target && stepLength<0){
            speed=target;
        }
        obj.style[attr]=speed+‘px‘;//每隔animationVelocity秒 移动stepLength px
        if(speed==target){//停止移动
            clearInterval(obj.timer);
        }
    },animationVelocity);
}

function getStyle(obj,attr){//为什么要parseInt(),因为obj.currentStyle[attr] 拿到的是30px -->30 拿到元素的属性的值 如位置等信息
    return parseInt(obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr]) ;
}

 

2016-06-01 抖动

标签:

原文地址:http://www.cnblogs.com/bravolove/p/5551109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!