0
我有代碼設置爲在屏幕不活動2秒後啓動動畫(我基本上在做一個屏幕保護程序)。但我無法弄清楚如何停止動畫和DIV回到正常後,屏幕不再空閒(鼠標移動,屏幕上輕點,等)在屏幕活動後停止動畫
這裏的的jsfiddle - http://jsfiddle.net/Xw29r/7129/
我的代碼:
var timeoutID;
function setup() {
this.addEventListener("mousemove", resetTimer, false);
this.addEventListener("mousedown", resetTimer, false);
this.addEventListener("keypress", resetTimer, false);
this.addEventListener("DOMMouseScroll", resetTimer, false);
this.addEventListener("mousewheel", resetTimer, false);
this.addEventListener("touchmove", resetTimer, false);
this.addEventListener("MSPointerMove", resetTimer, false);
startTimer();
}
setup();
function startTimer() {
// wait 2 seconds before calling goInactive
timeoutID = window.setTimeout(goInactive, 2000);
}
function resetTimer(e) {
window.clearTimeout(timeoutID);
goActive();
}
function goInactive() {
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $('#wrap').height() - 50;
var w = $('#wrap').width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
}
function goActive() {
startTimer();
}
你真棒!有什麼方法可以改變動畫的速度嗎?我需要它慢! – user3667051
在'animateDiv'函數中,您可以設置恆定速度,如果您將其更改爲1000,那麼它將移動1秒。 – Oen44