我想編寫一個函數來慢慢地在屏幕上移動的圖像。相關的HTML如下:不能調用JavaScript函數兩次
var dom, timer;
function initImage() {
dom = document.getElementById('animate').style;
dom.position = 'absolute';
dom.top = "165px";
dom.left = "767px";
regulate(1115,165);
regulate(1115,540);
regulate(767,540);
regulate(767, 165);
}
function regulate(xfinal, yfinal) {
var timer = setInterval(function() {moveImage(xfinal,yfinal)}, 1);
return true;
}
function moveImage(xfinal, yfinal) {
var x = parseInt(dom.left.match(/\d+/));
var y = parseInt(dom.top.match(/\d+/));
if ((x == xfinal) && (y== yfinal)) {clearInterval(timer);}
else {
if (x != xfinal) {
if (x < xfinal) {x++;}
else {x--;};
dom.left = x + "px";}
else {
if (y < yfinal) {y++;}
else {y--;};
dom.top = y + "px";};
};
return true;
}
<img src='http://placehold.it/200' alt='Sir Victor' width=50 height=50
id='animate' onload='initImage();' style='position:absolute;'/>
該算法能正常工作的第一個函數調用來調節(),但是當我去掉了其他三個中的一個,並嘗試運行它時,圖像要麼完全不移動,要麼移動的速度比正常快,但只能沿着第一條路徑移動。第二次功能是否有預期的作用?
我是新來的JavaScript,可以隨意地指出其他看似愚蠢的或過分複雜的爲好。
可以提供plunkr這個代碼? –
您需要將'timer'在全球範圍內,以及(給你兩個'moveImage'和'regulate'引用它。(可能不是問題,但它至少是一個問題。 –
你逝去的計時器它被分配一個值! – wallop