scrollTo.js 888 B

123456789101112131415161718192021222324252627282930313233
  1. $.fn.scrollTo = function(options) {
  2. var defaults = {
  3. toT: 0, //滚动目标位置
  4. durTime: 500, //过渡动画时间
  5. delay: 30, //定时器时间
  6. callback: null //回调函数
  7. };
  8. var opts = $.extend(defaults, options),
  9. timer = null,
  10. _this = this,
  11. curTop = _this.scrollTop(), //滚动条当前的位置
  12. subTop = opts.toT - curTop, //滚动条目标位置和当前位置的差值
  13. index = 0,
  14. dur = Math.round(opts.durTime / opts.delay),
  15. smoothScroll = function(t) {
  16. index++;
  17. var per = Math.round(subTop / dur);
  18. if (index >= dur) {
  19. _this.scrollTop(t);
  20. window.clearInterval(timer);
  21. if (opts.callback && typeof opts.callback == 'function') {
  22. opts.callback();
  23. }
  24. return;
  25. } else {
  26. _this.scrollTop(curTop + index * per);
  27. }
  28. };
  29. timer = window.setInterval(function() {
  30. smoothScroll(opts.toT);
  31. }, opts.delay);
  32. return _this;
  33. };