如何向一个按钮添加两个事件侦听器/操作

时间:2014-04-03 02:18:32

标签: javascript

我正在尝试暂停并播放“按钮”,但我不知道该怎么做。我猜它需要知道一次点击是活跃的切换到另一个,但我不知道如何做到这一点。

// Initialize variables

var button = document.getElementById("button");
var button2 = document.getElementById("button2");
var rect = document.getElementById("rect");
var polygon = document.getElementById("polygon");
var circle = document.getElementById("circle");


// Define functions

function play() {
    rect.setAttribute("class", "anim");
    polygon.setAttribute("class", "anim");
    circle.setAttribute("class", "anim");

}

function pause() {
    rect.setAttribute("class", "pause");
    polygon.setAttribute("class", "pause");
    circle.setAttribute("class", "pause");
}

// Add event listeners

button.addEventListener("click", play, false);

button2.addEventListener("click", pause, false);

2 个答案:

答案 0 :(得分:1)

您可以改为编写切换处理程序:

function playPause()
{
    if (this.playState) {
        rect.className = polygon.className = circle.className = 'pause';
    } else {
        rect.className = polygon.className = circle.className = 'anim';
    }
    // update button text to indicate state?
    this.playState = !this.playState;
}

它在DOM元素本身上保持状态,并在暂停和播放之间切换。

答案 1 :(得分:0)

如果您使用两个不同的按钮,请尝试此操作,

    var isplaying = false;
    function play() {
    isplaying = true;
        rect.setAttribute("class", "anim");
        polygon.setAttribute("class", "anim");
        circle.setAttribute("class", "anim");

    }

    function pause() {
isplaying = false;
        rect.setAttribute("class", "pause");
        polygon.setAttribute("class", "pause");
        circle.setAttribute("class", "pause");
    }

    // Add event listeners

    button.addEventListener("click",function(){ if(!isplaying){
button.disable(); button2.enable(); play();}});

    button2.addEventListener("click",function(){ if(isplaying){
button2.disable(); button.enable(); pause();}});