Greasy Fork

Greasy Fork is available in English.

YouTube 首页视频排列数量调整

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

当前为 2025-05-04 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==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 });
})();