MediaWiki:Gadget-Backtotop.js

来自康健生活
Kangkk​(留言 | 贡献)2020年2月18日 (二) 11:38的版本 (创建页面,内容为“// <pre> →回到顶部:​ $(function() { var body = document.body, html = document.documentElement; var innerWidth = window.innerWidth; var scr…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
  • Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
// <pre>
/* 回到顶部 */
$(function() {
    var body = document.body,
        html = document.documentElement;
    var innerWidth = window.innerWidth;
    var scrollbarWidth;
    switch ("scroll") {
        case getComputedStyle(body).overflowY:
            scrollbarWidth = innerWidth - body.clientWidth;
            break;
        case getComputedStyle(html).overflowY:
            scrollbarWidth = innerWidth - html.clientWidth;
            break;
        default:
            var backup = body.style.overflowY;
            body.style.overflowY = "scroll";
            scrollbarWidth = innerWidth - body.clientWidth;
            body.style.overflowY = backup;
    }
    var btn = $("<div/>", {
        "text": "返回顶部",
        "attr": {
            "title": "返回顶部",
            "class": "backToTop"
        },
        "css": {
            "user-select": "none"
        },
        "on": {
            "click": function() {
                $("html, body").animate({
                    scrollTop: 0
                }, 120);
            }
        }
    }).appendTo(document.body);
    if (scrollbarWidth === 0) {
        btn.css("right", "20px"); // 修复新版 Chrome 的自动隐藏式滚动条导致的按钮被覆盖 chrome://flags/#overlay-scrollbars
    }
    $(window).on("scroll", function() {
        $(document).scrollTop() > 0 ? btn.fadeIn() : btn.fadeOut();
    }).scroll();
});
// </pre>