如何使用mouseup在javascript中触发倒计时

时间:2015-11-07 11:42:40

标签: javascript mouseevent countdown

我尝试从mouseup上的任意给定数字计数到0,以设置src标记的img属性的动画。

var count = 0,
    direction = 1,
    image = document.getElementById('myImage'),
    mousedownID = -1; 

function mousedown(event) {
    if(mousedownID==-1) 
       mousedownID = setInterval(whilemousedown, 150);
}

function mouseup(event) {
    if(mousedownID!=-1) {
      mousedownID = setInterval(after, 150);
      clearInterval(mousedownID);
      mousedownID=-1;
    }
}

function whilemousedown() {
    image.src = "block-" + count + ".png";

    count += direction;
    direction *= (((count % 11) == 0) ? -1 : 1);
}

function after() {
    image.src = "block-" + count + ".png";
    count = count - 1;
    if(count = 0){
      clearInterval(mousedownID);
    }
}

document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
document.addEventListener("mouseout", mouseup);

点击鼠标时,12个图像被动画,1 ... 12 ... 1 ... 12 ...依此类推,现在我想将它动画回第一个图像,一旦我释放鼠标按钮。

1 个答案:

答案 0 :(得分:0)

你可以使用两个setInterval,一个只是增加/减少,另一个只是减少:

var limit = 11,
    count = 0,
    direction = -1,
    image = document.getElementById('myImage'),
    mousedownID = -1,
    mouseupID = -1; 

function mousedown(event) {
    if(mousedownID == -1) {
        if (mouseupID != -1) {
            clearInterval(mouseupID);
            mouseupID = -1;
        }

        mousedownID = setInterval(whilemousedown, 150);
    }
}

function mouseup(event) {
    if(mousedownID != -1) {
        clearInterval(mousedownID);
        mousedownID = -1;

        if (mouseupID == -1) {
            direction = -1;  // delete this if you prefer
            mouseupID = setInterval(after, 150);
        }
    }
}

function whilemousedown() {
    image.src = "block-" + count + ".png";

    if (count == 0) {
        direction = +1;
    } else if (count == limit) {
        direction = -1;
    }

    count += direction;
}

function after() {
    if (count == 0) {
        clearInterval(mouseupID);
        mouseupID = -1;
        return;
    }

    count = count - 1;
    image.src = "block-" + count + ".png";
}

document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
document.addEventListener("mouseout", mouseup);