具有最大值和最小值的 jQuery 计数器



我正在构建一个计数器,当我鼠标按下时,它应该递增到最大值,递减不超过 0。我还有一个选项可以将计数器重置为其初始值:0。 此外,如果 maxValue 是偶数,它应该计数到该数字。但是,如果 maxValue 是奇数,则它应该计数到数字 1。

计数器似乎工作正常。但有时它往往会停留在两个值之间。我很确定当我将鼠标悬停在其中一个按钮上然后立即在另一个按钮上鼠标时,就会发生这种情况。有没有办法防止这种情况发生? 我还想知道我的代码是否正确,如果有更简单的方法(也许有循环(?

无论如何,这是我的代码:

$(document).ready(function(){
var maxValue = 3;
var count = 0;
// intervals used to regulate how fast the value will change on mousedown
var upInterval;
var downInterval;
$('#counter').html("<p>" + parseInt(count) + "</p>");
$('#up').mousedown(function(){
 // if the maxValue is an even number
 if(maxValue % 2 == 0) {
    upInterval = setInterval(function(){
        if(count < maxValue) {
            count++;
            $('#counter').html("<p>" + parseInt(count) + "</p>");
        }
    },180);
  }
// if it's an odd number, subtract one
 else {
    upInterval = setInterval(function(){
        if(count < maxValue-1) {
            count++;
            $('#counter').html("<p>" + parseInt(count) + "</p>");
        }
    },180);
 }
}).mouseup(function() {
    clearInterval(upInterval);       
}); 
$('#down').mousedown(function(){
    downInterval = setInterval(function(){
        if(count > 0) {
            count--;
            $('#counter').html("<p>" + parseInt(count) + "</p>");
        }
    },180);
}).mouseup(function() {
    clearInterval(downInterval);    
});
    $('#reset').click(function(){
        count = 0;
        $('#counter').html("<p>" + parseInt(count) + "</p>");
    });
});

请记住,间隔是为了调节我按下鼠标时数字的变化速度,并阻止它增加或减少。

这是一个小提琴

谢谢!

jsBin 演示(高级用例(

在上面的演示中,我创建了一个用例,您可以在其中处理多个元素。它还具有更好的用户体验,因为它使用 setTimeout(而不是间隔(,只要您持有它,它就会逐渐提高计数速度。

jsBin 演示

$(document).ready(function(){
  var $counter = $("#counter p"), // Get the 'p' element
      max = 10,
      c   = 0,
      up  = true, // boolean // This will keep track of the clicked up/dn button
      itv; 
  function incDec(){
    c = up ? ++c : --c; // value of `up` is true? increment, else: decrement
    c = Math.min(Math.max(c, 0), max); // dididababaduuuu!
    $counter.text(c);                  // Set current `c` into element
  }
  $('#up, #down').on("mousedown", function(e){   
    up = this.id==="up";           // set to true if button in "up"; else: false
    incDec();                      // Trigger on sligle click
    clearInterval(itv);            // Clear some ongoing intervals
    itv=setInterval(incDec, 180);  // Do every 180 untill..
  }).on("mouseup mouseleave", function(){        //      ..mouseup or mouseleave
    clearInterval(itv); 
  });

  $('#reset').click(function(){
    c = 0;              // Reset to 0
    $counter.text(c);   // Show that "0"           
  }).click();           // Trigger a reset click on DOM ready
});
如果

元素本身没有发生"鼠标向上"(例如,在按下鼠标时将光标移出(,我只能重现您描述的"卡住"。所以这为我解决了它:

$('#up').mousedown(function(){
    $(window).mouseup(function() {
        clearInterval(upInterval);       
    });
  // if the maxValue is an even number
  ....
});
// and so on

最新更新