leftRightAnimate

by huahua

HTML

<div id="box"></div>
  <button id="leftBtn">left</button>
  <button id="rightBtn">right</button>
  <button id="stopBtn">stop</button>

CSS

#box {
    width: 100px;
    height: 100px;
    background-color: #f79;
    position: absolute;
    left: 200px;
    top: 50px;
  }

JavaScript

var
    box = document.getElementById("box"),
    leftBtn = document.getElementById("leftBtn"),
    rightBtn = document.getElementById("rightBtn"),
    stopBtn = document.getElementById("stopBtn");
  var
    leftMax = document.documentElement.clientWidth - box.offsetWidth,
    leftMin = 0;
  var
  	// 当前位置
    cur,
    // 控制定时器的变量
    timer,
    // 每次移动的距离
    step = 1,
    // 时间片段的长度
    interval = 50;

  // leftBtn.onclick = moveLeft;
  // rightBtn.onclick = moveRight;
  leftBtn.onclick = function(){move(leftMin)};
  rightBtn.onclick = function(){move(leftMax)};
	stopBtn.onclick = moveStop;

 // 合并向左和向右的函数
  function move(target) {
    // 清除之前的动画
    window.clearTimeout(timer);
    // 去单位,变数字
    cur = rmPx(window.getComputedStyle(box, null).left) - 0;
    // 开始动画
    timer = window.setInterval(function() {
    	// 在超出目标值之后,清除定时器,且归置cur
      function afterTarget() {
        window.clearTimeout(timer);
        timer = null;
        cur = target;
      }
      // 目标值大于当前值的话就是向右
      if (target > cur) {
        cur += step;
        cur >= target && afterTarget();
      // 小于就是向左
      } else {
        cur -= step;
        cur <= target && afterTarget();
      }
      box.style.left = addPx(cur);
      console.log(cur);
    }, interval);
  }	
  function moveStop() {
    window.clearTimeout(timer);
  }
	
/*
  function moveRight() {
  	// 清除之前的动画
    window.clearTimeout(timer);
    // 去单位,变数字
    cur = rmPx(window.getComputedStyle(box, null).left) - 0;
    // 开始动画
    timer = window.setInterval(function() {
        cur += step;
        // 限定范围
        if (cur >= leftMax) {
          window.clearTimeout(timer);
          timer = null;
          cur = leftMax;
        }
        box.style.left = addPx(cur);
        console.log(cur);
      }, interval);
  }

  function moveLeft() {
    window.clearTimeout(timer);
    cur = rmPx(window.getComputedStyle(box, null).left) - 0;
    timer = window.setInterval(function() {
        cur -= step;
        if (cur <= leftMin) {
  ...