关于javascript:js滚动浏览器滚动条js滚动元素滚动条

1次阅读

共计 2096 个字符,预计需要花费 6 分钟才能阅读完成。

该代码能够实现滚动 浏览器 任意 dom 元素 程度方向 垂直方向 的滚动条至指定地位。
常见场景有:置顶 置底
滚动成果:
程度方向滚动

垂直方向滚动

代码:

/**
   * 设置浏览器或元素滚动条滚动间隔
   * @param ele dom 元素或 window 对象
   * @param direction 滚动条方向,默认为 y,可选值有:x、y
   * @param to 滚动条行将滚动到到地位
   * @param duration 时长(可选)* @param onDone 实现后的回调(可选)* @param onScroll 正在滚动中的回调(可选)* @returns {boolean}
   */
function scrollTo (ele, direction, to, duration, onDone, onScroll) {if (!ele) {return false;}
    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = (
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback) {return window.setTimeout(callback, 1000/60);
        }
      );
    }
    if (!direction) {direction = 'y';}
    direction = direction == 'x' ? 'x' : 'y';
    var doDone = function () {if (typeof onDone == 'function') {onDone();
      }
    }
    var callOnScroll = function () {if (typeof onScroll == 'function') {onScroll();
      }
    }
    var attr = direction == 'x' ? 'scrollLeft' : 'scrollTop';
  var scrollLeft = function (ele) {if (ele && ele.nodeType == 1) {return ele.scrollLeft;}
    return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
  }
  var scrollTop = function (ele) {if (ele && ele.nodeType == 1) {return ele.scrollTop;}
    return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  }
    if (!duration || duration <= 0) {if (ele === window) {window.scrollTo(direction === 'x' ? to : scrollLeft(), direction === 'y' ? to : scrollTop());
      } else {ele[attr] = to;
      }
      callOnScroll();
      doDone();
      return true;
    }

    var diff = to - ele[attr];
    if (ele === window) {diff = to - (direction == 'x' ? scrollLeft() : scrollTop());
    }
    var perTick = (diff / duration) * 10;
    window.requestAnimationFrame(function () { // 实现缓动成果
      if (ele === window) {let x = scrollLeft();
        let y = scrollTop();
        window.scrollTo(direction === 'x' ? (x + perTick) : x, direction === 'y' ? (y + perTick) : y);
        callOnScroll();
        if (direction == 'x' ? scrollLeft() : scrollTop() !== to) {scrollTo(ele, direction, to, duration - 10, onDone, onScroll);
        } else {callOnScroll();
          doDone();}
        return;
      }
      ele[attr] += perTick;
      if (ele[attr] !== to) {callOnScroll();
        tool.scrollTo(ele, direction, to, duration - 10, onDone, onScroll);
      } else {callOnScroll();
        doDone();}
    });
    return true;
  }

调用:

var ele = document.getElementById('xxx');
// 滚动至元素最右侧
scrollTo(ele, 'x', ele.scrollWidth, 200);
// 滚动至元素顶部
scrollTo(ele, 'y', 0, 200);

// 滚动至浏览器顶部
scrollTo(window, 'y', 0, 200);
正文完
 0