點擊一個固定按鈕,平滑的滾動到窗口頂部的這種功能,在前端開發是相當常見的,如圖:

關鍵代碼:
$.fn.scrollTo = function(options) {   var defaults = {     toT: 0, //滾動目標位置     durTime: 500, //過渡動畫時間     delay: 30, //定時器時間     callback: null //回調函數   };   var opts = $.extend(defaults, options),     timer = null,     _this = this,     curTop = _this.scrollTop(), //滾動條當前的位置     subTop = opts.toT - curTop, //滾動條目標位置和當前位置的差值     index = 0,     dur = Math.round(opts.durTime / opts.delay),     smoothScroll = function(t) {       index++;       var per = Math.round(subTop / dur);       if (index >= dur) {         _this.scrollTop(t);         window.clearInterval(timer);         if (opts.callback && typeof opts.callback == 'function') {           opts.callback();         }         return;       } else {         _this.scrollTop(curTop + index * per);       }     };   timer = window.setInterval(function() {     smoothScroll(opts.toT);   }, opts.delay);   return _this; };  //調用  $("body").scrollTo({ toT: 0 }); 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答