经常浏览网页,看到很多网站都有回到顶部的按钮,而有些网站没有这个功能,就想用脚本自己实现一下,这样所有页面都可以使用了。
// ==UserScript== // @name ToTop // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author JackMeng // @match http*://* // @include * // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== // @iconURL https://www.cnblogs.com/favicon.ico // @grant none // @run-at document-end // @noframes // ==/UserScript== //添加样式 function AddStyle() { var styleRule = $(`<style> .upShow { position: fixed; bottom: 6px; right: 4px; z-index: 1001; cursor: pointer; height: 35px; width: 35px; text-align: center; line-height: 35px; opacity: 0.8; border-radius: 50%;/*决定四角圆弧*/ box-shadow: 0 2px 4px 1px rgba(0,0,0,.6); background-color:red; transition: all .4s ease;/*延时变化*/ display: flex; align-items: center; flex-direction: column; } .upShow:hover{background-color: #0dd;} .upShow:hover .upArrow, .upShow:hover .upArrow:before, .upShow:hover .upArrow:after{border-color: #fff;} .upArrow { display: inline-block; border-width: 2px 0 0 0; border-color: #666; border-style: solid; font: normal normal normal 14px/1 FontAwesome; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; transition: all .4s ease;/*延时变化*/ background-color:transparent; height: 16px; width: 16px; margin: 10px 0; padding: 2px 0; } .upArrow:before{ content: ""; display: inline-block; height: 10px; width: 10px; transform: rotate(45deg); border-width: 2px 0 0 2px; border-color: #666; border-style: solid; } .upArrow:after{ content: ""; position: absolute; display: inline-block; height: 14px; right:16px; border-width: 0 0 0 2px; border-color: #666; border-style: solid; } </style>`).prependTo('html'); styleRule.attr('type', 'text/css'); styleRule.attr('id', 'arrowCss'); styleRule.append('#articleContentId{ color: red; }'); } //给页面添加元素 function AddElem() { var toTop=$(`<span id="gotoTop" class="upShow" title="返回顶部"> <i class="upArrow"></i> </span>`).prependTo($("body")); //toTop[0].onclick = ()=>gotoTop(500); //toTop[0].onclick = ()=>{getBlogData(21);} return toTop[0]; } function getBlogData(num) { var host = window.location.host; console.log("======================"+num); } function bindEvent(obj,minHeight){ // 定义点击返回顶部图标后向上滚动的动画 $("#gotoTop").click( function(){ $('html,body').animate({scrollTop:'0px'},'slow'); }); // 获取页面的最小高度,无传入值则默认为600像素 minHeight = minHeight ? minHeight : 600; // 为窗口的scroll事件绑定处理函数 $(window).scroll(function(){ // 获取窗口的滚动条的垂直滚动距离 var sTop = $(window).scrollTop(); // 当窗口的滚动条的垂直距离大于页面的最小高度时,让返回顶部图标渐现,否则渐隐 if( sTop > minHeight){ $("#gotoTop").fadeIn(300); }else{ $("#gotoTop").fadeOut(300); } }); } (function(){ 'use strict'; // Your code here... if (window.top == window.self) { //插入样式 AddStyle(); //插入元素 var a = AddElem(); bindEvent(a,100); } })();
标签:脚本,function,width,顶部,2px,upArrow,color,border,油猴 From: https://www.cnblogs.com/mq0036/p/17758332.html