JavaScript如何在转换结束前阻止点击

时间:2016-01-22 15:25:45

标签: javascript

点击后我想要更改背景,但是如何阻止点击直到转换完成?

var box = document.querySelector('.box');

var colors = ['red', 'green', 'blue'];
var i = 0;

box.addEventListener('click', function() {
    box.style.background = '' + colors[i] + '';
    console.log(colors[i]);

    i++;
    if (i == 3) {
      i = 0;
    }
});

代码: http://jsbin.com/nizufi/2/edit?html,css,js,output

1 个答案:

答案 0 :(得分:1)

您可以使用JavaScript事件transitionend

var box = document.querySelector('.box');
var colors = ['red', 'green', 'blue'];
var i = 0;
var transitioning = false;

box.addEventListener('click', function() {
    if(transitioning) {
      return;
    }

    box.style.background = '' + colors[i] + '';
    console.log(colors[i]);

    i++;
    if (i == 3) {
        i = 0;
    }

    transitioning = true;
});

box.addEventListener('transitionend', function () {
  transitioning = false;
});