使用 jquery 移动 div 按钮时,设置增加边距的最大值

Set a max value for increasing margin when moving a div on button click with jquery

我有两个按钮。单击时,它们会上下移动 div:

点击按钮时div向下移动,我想设置一个最大值

$('.button_down').click(function() {
    $('.whole_car_body').animate({
      marginTop : "+=2px"
    });
});

点击按钮时div向上移动,我想设置一个最大值

$('.button_up').click(function() {
    $('.whole_car_body').animate({
      marginTop : "-=2px"
    });
});

我想设置一个最大值,所以当达到最大值时应该停止 increasing/decreasing。谢谢。

有几种方法可以做到这一点。一个相对简单的方法是使用一个变量 "count" 和一个变量来存储最大值。即:

var maximumDivIncrease = 50;
var currentDivIncrease = 0;
$('.button_up').click(function() {
    if(currentDivIncrease < maximumDivIncrease) {
        currentDivIncrease += 2;
        $('.whole_car_body').animate({
          marginTop : "-=2px"
        });
    }
});

这样它会先检查变量,如果低于最大值就增加它,否则什么都不做。要为向下按钮执行此操作,您只需减少数量并添加最小值。

它运行得非常完美。

var maximumDivIncrease = 6;
var currentDivIncrease = 0;
$('.button_up').click(function() {
    if(currentDivIncrease < maximumDivIncrease) {
        currentDivIncrease += 2;
        $('.whole_car_body').animate({
          marginTop : "-=2px"
        });
    }
});

var minimumDivIncrease = -6;
$('.button_down').click(function() {
    if(currentDivIncrease > minimumDivIncrease) {
        currentDivIncrease -= 2;
        $('.whole_car_body').animate({
          marginTop : "+=2px"
        });
    }
});