如何停止递增达到特定数量的Mousedown事件

时间:2018-12-02 00:18:53

标签: javascript jquery html css

您能否让我知道在达到特定基准时如何中断,杀死或停止mousedown事件?

对于以下代码中的eaxmole,我想在temp击中30时禁用键和事件

$(document).ready(function() {
  var temp = 0;
  var to = null;
  var iv = null;

  $("#ClickMe").on("mousedown", function() {
    temp++;
    $("#Temp").html(temp);
    to = setTimeout(function() {
      iv = setInterval(function() {
        temp++;
        $("#Temp").html(temp);
      }, 75);
    }, 500);
  }).on("mouseup mouseleave", function() {
    clearTimeout(to);
    clearInterval(iv);
  });
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="ClickMe">CLICK ME</button>
<div id="Temp">0</div>

2 个答案:

答案 0 :(得分:0)

添加一个House语句,然后使用jQuery的if方法:

.off()
$(document).ready(function() {
  var temp = 0;
  var to = null;
  var iv = null;

  $("#ClickMe").on("mousedown", function() {
    if (temp < 30) {
      temp++;
      $("#Temp").html(temp);
      to = setTimeout(function() {
        iv = setInterval(function() {
          temp++;
          $("#Temp").html(temp);
        }, 75);
      }, 500);
    } else {
      $("#ClickMe").off("mousedown");
    }
  }).on("mouseup mouseleave", function() {
    clearTimeout(to);
    clearInterval(iv);
  });
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}

答案 1 :(得分:0)

好的,完整的答案,加上代码...

$(document).ready(function() {
  var temp = 0;
  var to = null;
  var iv = null;

  $("#ClickMe")
  .on("mousedown", function() {
    temp++;
    $("#Temp").html(temp);
    to = setTimeout(function() {
      iv = setInterval(moreClick, 75);
    }, 500);
  })
  .on("mouseup mouseleave", function() {
    clearTimeout(to);
    clearInterval(iv);
    test_stopClick();
  });

  function moreClick() {
    $("#Temp").html(++temp);
    test_stopClick();
  }

  function test_stopClick() {
    if (temp >= 30 ) {
      clearTimeout(to);
      clearInterval(iv);
      $("#ClickMe")
      .off("mousedown mouseup mouseleave")
      .prop('disabled', true);
    }
  }
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="ClickMe">CLICK ME</button>
<div id="Temp">0</div>