Greasy Fork

Greasy Fork is available in English.

自动适应屏幕大小

自动将页面宽度调整为适合屏幕大小的宽度,左右保留一定边距

当前为 2024-03-13 提交的版本,查看 最新版本

// ==UserScript==
// @name        自动适应屏幕大小
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  自动将页面宽度调整为适合屏幕大小的宽度,左右保留一定边距
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_notification
// @namespace http://greasyfork.icu/users/13961
// ==/UserScript==
(function() {
    var SCROLLBAR_ADJUST = 16; // Scrollbar width adjustment
    var MARGIN = 16; // Margin adjustment on each side of the content

    var isFit = GM_getValue('isFit', true); // Whether to enable adaptive width

    function addPreWrapCSS() {
        var style = document.createElement('style');
        style.innerHTML = 'pre { white-space: pre-wrap; }';
        document.head.appendChild(style);
    }

    function iter(elems, f) {
        for (var i = 0; i < elems.length; i++) {
            var e = elems[i];
            f(e); // Apply function f to element e
        }
    }

    function fit() {
        addPreWrapCSS();
        var elements = document.querySelectorAll('*');
        
        var availableWidth = window.innerWidth - SCROLLBAR_ADJUST - (MARGIN * 2);
        
        iter(elements, function(e) {
            var maxElementWidth = availableWidth + 'px';
            if (e.offsetWidth > window.innerWidth - SCROLLBAR_ADJUST) {
                e.style.width = 'calc(100% - ' + (MARGIN * 2) + 'px)';
                e.style.boxSizing = 'border-box';
                e.style.marginLeft = MARGIN + 'px';
                e.style.marginRight = MARGIN + 'px';
            } else {
                e.style.width = maxElementWidth;
                e.style.marginLeft = MARGIN + 'px';
                e.style.marginRight = MARGIN + 'px';
            }
        });
    }

    function applyFit() {
        isFit = !isFit;
        GM_setValue('isFit', isFit);
        GM_notification('自适应宽度状态已更新:' + (isFit ? '开启' : '关闭'), '自适应宽度', '', null);
        if (isFit) {
            fit(); // Apply width fitting if enabled
        }
    }

    function processMessage(event) {
        if (event.data.cmd === 'toggle') {
            applyFit();
        }
    }

    window.addEventListener('resize', function() {
        if (isFit) {
            fit();
        }
    });

    window.addEventListener('message', processMessage, false);

    // Toggle the fit on mouse double click
    window.addEventListener('dblclick', function() {
        applyFit();
    });

    // Apply fit on initial load if enabled
    if (isFit) {
        fit();
    }

    // Listen for the click event on the 'View more answers' button, if present
    var btn = document.querySelector('.QuestionMainAction');
    if (btn) {
        btn.addEventListener('click', function() {
            // Delay fit until content load after clicking
            setTimeout(fit, 1000);
        });
    }
})();