Greasy Fork

Greasy Fork is available in English.

YouTube 首页视频排列数量调整

调整YouTube首页每行视频数量,可自定义数量。

目前为 2025-05-04 提交的版本。查看 最新版本

// ==UserScript==
// @name         YouTube 首页视频排列数量调整
// @namespace    https://www.acy.moe
// @supportURL   https://www.acy.moe
// @version      1.0.2
// @description  调整YouTube首页每行视频数量,可自定义数量。
// @author       NEET姬
// @match        *://www.youtube.com/*
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// @license      GPL-3.0-only
// ==/UserScript==

(function () {
    'use strict';

    const STORAGE_KEY = 'yt_grid_columns';
    const DEFAULT_COLUMNS = 6;

    // 获取列数设置
    function getColumns() {
        return parseInt(localStorage.getItem(STORAGE_KEY)) || DEFAULT_COLUMNS;
    }

    // 设置列数并更新样式
    function setColumns(n) {
        localStorage.setItem(STORAGE_KEY, n);
        applyGridStyle(n);
    }

    // 注入 CSS 样式
    function applyGridStyle(columns) {
        const styleId = 'yt-grid-style';
        let styleTag = document.getElementById(styleId);
        if (!styleTag) {
            styleTag = document.createElement('style');
            styleTag.id = styleId;
            document.head.appendChild(styleTag);
        }
        styleTag.textContent = `
            ytd-rich-grid-renderer {
                --ytd-rich-grid-items-per-row: ${columns} !important;
            }
            ytd-rich-grid-video-renderer {
                max-width: ${Math.floor(1200 / columns)}px !important;
                zoom: 0.9 !important;
            }
            ytd-app {
                overflow-x: hidden !important;
            }
        `;
    }

    // 创建 Tampermonkey 设置菜单
    function createSettingsMenu() {
        GM_registerMenuCommand("设置每行视频数量", function() {
            const columns = prompt("请输入每行视频数量(4-8之间)", getColumns());
            if (columns >= 4 && columns <= 8) {
                setColumns(parseInt(columns));
            } else {
                alert("请输入一个有效的数字(4-8之间)!");
            }
        });
    }

    // 初始化
    function init() {
        applyGridStyle(getColumns());
        createSettingsMenu();
    }

    // 等待页面加载后初始化
    const observer = new MutationObserver(() => {
        if (document.querySelector('ytd-rich-grid-renderer')) {
            init();
            observer.disconnect();
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();