The content of this article is about the implementation principle of jitter in js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The implementation principle of dithering is actually to offset the position of node elements, so when implementing this function, it is best to absolute position the node elements and then modify their top and left value.
There are several key points here. The first is to prepare the frequency that needs to be offset. This can be controlled by putting the offset distance into an array. The smaller the offset distance, the smoother the effect. . The timer time determines the speed of node flapping.
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Made with Thimble</title> <link rel="stylesheet" href="style.css"> <style> img{ width:300px; height: 400px; position:absolute; top:20px; left:150px; } </style> </head> <body> <img id="img1" src="https://newimg.uumnt.cc:8092/Pics/2017/0622/03/06.jpg"> </body> <script> var oImg = document.getElementById('img1'); oImg.onclick = function(){ //this 到函数里面作用域会变,这里赋值先变成局部 var that = this; shaking(that,'top',function(){ shaking(that,'left'); }); }; // 抖动函数封装 attr:left水平抖动 top:垂直抖动 function shaking(obj,attr,callback){ var pos = parseInt(getStyle(obj,attr)); var arr = []; var num = 0; for(var i=20;i>0;i-=2){ arr.push(i,-i); } arr.push(0); clearInterval(obj.shaking); obj.shaking = setInterval(function(){ obj.style[attr] = pos + arr[num] + 'px'; num ++; if(num === arr.length){ clearInterval(obj.shaking); callback && callback(); } },50); } // 获取节点对象的样式属性值 function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return window.getComputedStyle(obj,false)[attr]; } } </script> </html>
Related recommendations:
Parsing of execution context and variable objects in js
Summary of character methods and string operation methods in js (with code)
The above is the detailed content of The implementation principle of jitter in js (with code). For more information, please follow other related articles on the PHP Chinese website!