该代码能够实现滚动浏览器任意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);