Home  >  Article  >  Web Front-end  >  How to achieve image jitter effect

How to achieve image jitter effect

王林
王林forward
2020-08-19 17:15:317246browse

How to achieve image jitter effect

Requirement: When you click on the picture, the picture will shake left and right, and it can also shake up and down.

The specific code is as follows:

(Recommended tutorial: CSS tutorial)

html:

<img src="./img/19.jpg" alt="" id="img1">

css:

img {
    position: absolute;
    top: 200px;
    left: 300px;
}

js:

<script src="doMove.js"></script>
<script>
    window.onload = function(){
        var img1 = document.getElementById(&#39;img1&#39;);

        img1.onclick = function(){
            // 先获得img1的原来left值,在此基础上进行抖动;parseInt()是把300px的单位去掉只留数字
            var pos = parseInt(getStyle(img1,&#39;left&#39;));
            var arr = [];//20,-20,18,-18,16,-16,...存放抖动的频率
            var timer = null;//开启定时器
            var num = 0;//一般只要有数组,那么必定有数字跟着变化;数组的第0个,第1个...

            for(var i =20;i>0;i-=2){//左右抖动的幅度第一次为20px,然后减2
                arr.push(i,-i);
            }
            arr.push(0);
            // alert(arr);//测试一下
            // 有抖动的频率之后,要开启定时器让它进行抖动
            clearInterval(timer);//开启定时器之前要先把定时器关闭,防止连续多次点击
            timer = setInterval(function(){
                img1.style.left = pos + arr[num] + &#39;px&#39;;//原来的位置pos,加上数组中每一个数字
                num++;
                if(num === arr.length){//如果数字等于数组的长度(就是全部抖完了),关闭定时器
                    clearInterval(timer);
                }
            },50);
        }
    }
</script>

Instructions:

1. We must first introduce our original encapsulated animation function doMove.js, and the getStyle() function is the function in this function;

2. parseInt() removes the 300px unit and leaves only the number 300;

3. To jitter up and down, just change left to top.

The above is the detailed content of How to achieve image jitter effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete