clearInterval函数实际上没有清除

时间:2016-11-24 18:09:55

标签: javascript jquery

div从左到右,从右到左滚动完成一轮,但卡在scrollBack()功能中。程序确实在所需的事件中执行clearInterval()语句,但它实际上并没有清除间隔。我做错了什么?

var backint = null;

function scrollForward() {
  if ($("#foo").scrollLeft() != $("#foo").width()) {
    $("#foo").scrollLeft($("#foo").scrollLeft() + 1);
  } else {
    backint = setInterval(scrollBack, 5);
  }
}

function scrollBack() {
  if ($("#foo").scrollLeft() != 0) {
    $("#foo").scrollLeft($("#foo").scrollLeft() - 1);
  } else if ($("#foo").scrollLeft() == 0) {
    clearInterval(backint);
  }
}

1 个答案:

答案 0 :(得分:0)

建议使用 .animate()作为Rory McCrossan做得更好,因为setInterval重新实现现有的东西而不一定更好:



var foo = $("#container"),
  bar = $("#foo"),
  scrollSize = bar.width() - foo.width();;

function scrollForward() {
  console.log('forward', foo.scrollLeft(), bar.width() - foo.width());
  if (foo.scrollLeft() != scrollSize) {
    foo.animate({
      scrollLeft: scrollSize + 'px'
    });
  }
}

function scrollBack() {
  console.log('back', foo.scrollLeft(), scrollSize);
  if (foo.scrollLeft() === scrollSize) {
    foo.animate({
      scrollLeft: '0px'
    });
  }
}

foo.on("click", scrollForward);
foo.on("dblclick", scrollBack);

#container {
  border: 1px solid #ccc;
  width: 410px;
  overflow-x: scroll;
  height: 50px;
}
#foo {
  background-color: #ccc;
  width: 1300px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="foo">Click to scroll right. Double-click to scroll left.</div>
</div>
&#13;
&#13;
&#13;