使用计数器和过渡效果禁用和启用单击事件

时间:2015-07-06 12:49:32

标签: javascript jquery html css

我的网页中有以下几行代码 - demo/example

HTML:

<button class="wrong-answer" onclick="showResult(this)">42</button>
<button class="right-answer" onclick="showResult(this)">43</button>

<p id="answer" class="answer-display-hidden">answer</p>

<div class="incorrect">
    <span>Incorrect:</span>
    <p>0</p>
</div>

<div class="correct">
    <span>Correct:</span>
    <p>0</p>
</div>

CSS:

.answer-display-visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}

.answer-display-hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

.incorrect, .correct {float: left; padding-right: 20px}

JS:

var incorrectCalls = 0;
var correctCalls = 0;

function showResult(b) {
  var res = document.getElementById('answer');

  if (b.classList.contains('right-answer')) {
    res.innerHTML = '<span class="right">right</span>';

    correctCalls++;
        var cor = $('.correct > p:first');
        cor[0].innerHTML = correctCalls;
  } 

  else {
    res.innerHTML = '<span class="wrong">wrong</span>';

    incorrectCalls++;
    var incor = $('.incorrect > p:first');
    incor[0].innerHTML = incorrectCalls;
  }

  res.classList.remove("answer-display-hidden");
  res.classList.add("answer-display-visible");

  setTimeout(function() {
        res.classList.add("answer-display-hidden");
  }, 2000);
}

如何在文本淡入和等待效果期间取消激活right-answer计数器,然后重新激活?这样用户就无法操作计数器(在显示文本之前快速单击按钮)。

2 个答案:

答案 0 :(得分:1)

单击按钮时可以使用setTimeout功能。

Live Demo

代码块:

function showResult(b) {
 .
 .
 .
  $(".right-answer").prop("disabled", true);
  $(".wrong-answer").prop("disabled", true);
  setTimeout(function() {
    $(".right-answer").prop("disabled", false);
    $(".wrong-answer").prop("disabled", false);
  }, 2600);
}

答案 1 :(得分:0)

这是我的解决方案

WORKING DEMO

删除了CSS代码,以下是jQuery代码。

$(document).ready(function(){

    $(".wrong-answer").click(function(){
        $(".right-answer").attr("disabled","disabled");
        $("#answer").text("WRONG").fadeIn(5000,function(){

            $(this).fadeOut(5000,function(){
                $(".right-answer").removeAttr("disabled");
            });
        })

    });

});