没有得到正确的值onclick

时间:2016-10-09 14:19:21

标签: javascript jquery html

我有一个滑块和左右两个按钮 我为每个按钮都有两个事件处理程序,我将在下面的代码中向您显示。

当我点击并等待转换完成时,everthing工作正常, 但是当我点击快速连续点击时,我得到的浮动不是预期的确切数字(如下面的HTML所示)

这是Javascript和Jquery混合在一起:

var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");


    left.addEventListener("click", function(){
        var marginLeft = container.style.marginLeft;
        var parsedMarginLeft = parseInt(marginLeft);
        console.log(parsedMarginLeft);
        if(parsedMarginLeft > -800) {
            $('#container').animate({marginLeft: '-=200px'}, 0);
        }
    });



    right.addEventListener("click", function(){
        var marginLeft = container.style.marginLeft;
        var parsedMarginLeft = parseInt(marginLeft);
        console.log(parsedMarginLeft);

        if(parsedMarginLeft < 0) {
            $('#container').animate({marginLeft: '+=200px'}, 0);
        }
    });

这是我点击后获得的HTML:

<div id="container" style="width: 1800px; margin-left: -127.879px;">

</div>

1 个答案:

答案 0 :(得分:2)

您可以使用:animated选择器作为事件侦听器中的第一行来测试容器div是否正在运行动画:

&#13;
&#13;
var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");


left.addEventListener("click", function(){
  if ($('#container:animated').length == 0) {
    var marginLeft = container.style.marginLeft;
    var parsedMarginLeft = parseInt(marginLeft);
    console.log(parsedMarginLeft);
    if(parsedMarginLeft > -800) {
      $('#container').stop().animate({marginLeft: '-=200px'}, 0);
    }
  }
});



right.addEventListener("click", function(){
  if ($('#container:animated').length == 0) {
    var marginLeft = container.style.marginLeft;
    var parsedMarginLeft = parseInt(marginLeft);
    console.log(parsedMarginLeft);

    if (parsedMarginLeft < 0) {
      $('#container').animate({marginLeft: '+=200px'}, 0);
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="left">left</button>
<button id="right">right</button>
<div id="container" style="width: 1800px; margin-left: 0px;background-color: red;">
aaaaaaaaaaaaaaaaa
</div>
&#13;
&#13;
&#13;