Greasy Fork is available in English.
在网页上添加返回顶部按钮,有滑动效果,不会显得突兀
当前为
// ==UserScript==
// @name 滑动返回顶部按钮
// @namespace http://mofiter.com/
// @version 0.1
// @description 在网页上添加返回顶部按钮,有滑动效果,不会显得突兀
// @author mofiter
// @create 2018-07-22
// @require http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js
// @include http*://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
var canScrollMouseOver = false; //当鼠标在按钮上,但未点击时,页面是否自动向上滑动,true 为可以自动滑动,false 为不能自动滑动
var opacityMouseEnter = 0.8; //当鼠标在按钮上时,图片的不透明度,从 0.0(完全透明)到 1.0(完全不透明)
var opacityMouseLeave = 0.5; //当鼠标不在按钮上时,图片的不透明度,从 0.0(完全透明)到 1.0(完全不透明)
var displayHeight = 200; //网页在垂直方向向下滑动超过 displayHeight 时显示按钮,单位是像素
var animateTime1 = 500; //点击按钮时,网页滑动到顶部需要的时间,单位是毫秒
var animateTime2 = 2000; //鼠标在按钮上时,网页滑动到顶部需要的时间,单位是毫秒
var isClicked = false; //按钮是否被点击
var $ = $ || window.$;
var goTop = document.createElement("div");
goTop.className = "goTop";
goTop.innerHTML = "<img src='http://mofiter.com/img/back_to_top_button.png' style='width:30px;height:30px;'></img>"; //图片的宽和高可以修改,原始图片宽高均为 40px
goTop.style.display = "none";
goTop.style.position = "fixed";
goTop.style.bottom = "150px"; //距离网页底部 150px,可自行修改
goTop.style.right = "30px"; //距离网页右边 30px,可自行修改
goTop.style.cursor = "pointer"; //当鼠标在按钮上时变为手型
goTop.lastChild.style.opacity = opacityMouseLeave; //按钮初始透明度
document.getElementsByTagName("body")[0].appendChild(goTop);
goTop.addEventListener("click", function(){ //点击鼠标时,网页滑动到顶部
isClicked = true;
if(canScrollMouseOver) {
$('html,body').stop();
}
$('html,body').animate({scrollTop:'0px'},animateTime1);
})
goTop.addEventListener("mouseenter",function(){ //鼠标移入时透明度改变,如果 canScrollMouseOver 为 true,则网页可以自动向上滑动
isClicked = false;
if(canScrollMouseOver) {
$('html,body').animate({scrollTop:'0px'},animateTime2);
}
goTop.lastChild.style.opacity = opacityMouseEnter;
})
goTop.addEventListener("mouseleave",function(){ //鼠标移出时透明度改变,如果 canScrollMouseOver 为 true,并且按钮未被点击,停止网页自动向上滑动的动画
if(canScrollMouseOver && !isClicked) {
$('html,body').stop();
}
goTop.lastChild.style.opacity = opacityMouseLeave;
})
document.onscroll = function(){
if (getScrollTop() >= displayHeight){
$('.goTop').fadeIn(300); //按钮淡入,单位为毫秒
} else {
$('.goTop').fadeOut(300); //按钮淡出,单位为毫秒
}
}
function getScrollTop(){ //获取垂直方向滑动距离
var scrollTop=0;
if(document.documentElement&&document.documentElement.scrollTop){
scrollTop=document.documentElement.scrollTop;
}else if(document.body){
scrollTop=document.body.scrollTop;
}
return scrollTop;
}
})();