零JS筆記 | 定時器 | 抖動
setInterval(函數,毫秒);
clearInteval( setInterval(函數,毫秒); )
注意理解: num %= arr.length;
See the Pen vNBmeE by elmok (@elmok) on CodePen.
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
圖片切換實例更改
<a href='http://www.elmok.com/js/%E6%9C%80%E7%B0%A1%E5%96%AE%E7%9A%84%E5%9C%96%E7%89%87%E5%88%87%E6%8F%9B%E4%BA%8C.html
' target='_blank'>最簡單的圖片自動切換
function aplay(){
var timer = setInterval(function(){
num++;
num %= arrimg.length;//num = 0 1 2 3 4 === if(num = lis.length){num = 0}
tab()
},1000)
}
//去掉鼠標移入移出
box.onmouseover = function(){
clearInterval(timer)
};
box.onmouseout = aplay //不能加括號
//打開時隔2s後再執行;體驗
setTimeout(aplay,2000)
應用:打開網頁自動彈出;
setTimerout(函數,毫秒);
clearTimeout( setTimerout(函數,毫秒); )
var imgbox = document.getElementById('img')
setTimeout(function(){
imgbox.style.display = 'inline-block'; //圖片為 inline-block;
setTimeout(function(){ //3秒後關閉;
imgbox.style.display = 'none'
},3000)
},2000)
圖片鼠標按下自動滾動,抬起停止
onmousedown
onmouseup
See the Pen PPYmMj by elmok (@elmok) on CodePen.
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>
抖動函數
原理:原位置以遞減方式向兩邊相加,越加越小直到0;
抖完後執行回調~
//方法封裝
function shake(obj, attr, pos, endfn) {
// var pos = parseInt(getStyle(obj,attr)); //去掉ps //隱患,多次觸發時每次的初始位置不同;
var arr = []; //20 -20 18 -18
var shake = null;
var num = 0;
for (var i = 20; i > 0; i -= 2) {
arr.push(i, - i);
}
arr.push(0);
clearTimeout(obj.shake)
shake = setInterval(function () {
obj.style[attr] = pos + arr[num] + 'px'
num++
if (num == arr.length) {
clearInterval(obj.shake)
endfn && endfn()
}
}, 50)
}
var img = document.getElementsByTagName('img')
var on = true;
for (var i = 0; i < img.length; i++) {
img[i].style.left = 100 + i * 110 + 'px'
var pos = parseInt(getStyle(img[i], 'top'));
img[i].onmousemove = function () {
shake(this, 'top', pos)
}
}
<img src="c1.jpg" alt="" width="150"/>
<img src="c2.jpg" alt="" width="150"/>
<img src="c3.jpg" alt="" width="150"/>
<img src="c4.jpg" alt="" width="150"/>
<img src="c5.jpg" alt="" width="150"/>
修復版:
function shake(obj, attr, endfn) {
if (obj.door) {
return
}
obj.door = 1;
var pos = parseInt(css(obj,attr));
var arr = []; //20 -20 18 -18
var num = 0;
for (var i = 20; i > 0; i -= 2) {
arr.push(i, - i);
}
arr.push(0);
clearTimeout(obj.shake)
obj.shake = setInterval(function () {
obj.style[attr] = pos + arr[num] + 'px'
num++
if (num == arr.length) {
clearInterval(obj.shake)
endfn && endfn()
obj.door = 0;
}
}, 50)
}