一般如果网页特别长的话,经常在页面的右下角会有一个按钮,点击一下滚动条就自动的回到最上面的位置
实现方式的话其实非常的简单,就是监听onscroll事件,然后判断下当前滚动高度,如果需要返回到顶部就把scorllTop设置为0就滚动到顶部了
这里推荐一个简单好用的jq库jQuery.toTop, 源码附在下面了加了点注释。
/**
* Plugin Name: jQuery toTop for smoothly Scroll back to Top
* Plugin URL: https://github.com/mmkjony/jQuery.toTop
* Version: 1.1
* Author: MMK Jony
* Author URL: https://github.com/mmkjony
* License: Licensed under MIT
**/
(function( $ ){
'use strict';
$.fn.toTop = function(opt){
// 内部使用的参数
var elem = this;
var win = $(window); // jq窗口对象
var doc = $('html, body'); // jq的body对象
// 额外配置项
var options = $.extend({
autohide: true,
offset: 420,
speed: 500,
position: true,
right: 15,
bottom: 30
}, opt); // opt没有时使用上面的默认值
elem.css({
'cursor': 'pointer'
});
// 回滚按钮是否自动隐藏
if(options.autohide){
elem.css('display', 'none');
}
// 使用内置的布局定位方式,否者自己使用css来做布局定位
if(options.position){
elem.css({
'position': 'fixed',
'right': options.right,
'bottom': options.bottom,
});
}
// 点击回滚按钮后,将scrollTop设置为0,用时500ms,这样会有一个滚动上去的动画效果
elem.click(function(){
doc.animate({scrollTop: 0}, options.speed);
});
// jq的http://api.jquery.com/scroll
win.scroll(function(){
var scrolling = win.scrollTop();
// 当页面在顶部区域时隐藏回滚按钮,比较靠页面下部时显示回滚按钮
if(options.autohide){
if(scrolling > options.offset){
elem.fadeIn(options.speed);
}
else elem.fadeOut(options.speed);
}
});
};
}( jQuery ));