Skip to main content

给网站设置背景颜色

给Twitter网站设置背景颜色

// ==UserScript==
// @name 修改twitter背景色
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 修改twitter背景色
// @author You
// @match https://x.com/*
// @grant none
// @run-at document-start
// ==/UserScript==

(function() {
'use strict';

// 创建style元素并注入CSS
const style = document.createElement('style');
style.textContent = `
body {
background-color: #f9f6e7 !important;
}

/* 同时修改CSS变量,确保兼容性 */
:root {
--background: 249 246 231 !important;
}
`;

// 将样式添加到head中
function addStyle() {
if (document.head) {
document.head.appendChild(style);
return true;
}
return false;
}

// 如果head已存在,直接添加
if (addStyle()) {
return;
}

// 否则等待head元素出现
const observer = new MutationObserver(() => {
if (addStyle()) {
observer.disconnect();
}
});

observer.observe(document, {
childList: true,
subtree: true
});
})();
  1. 先试第二个方案(CSS注入版本) - 这个最可靠,因为它直接注入CSS样式,优先级更高
  2. 如果还不行,试第一个方案(JavaScript设置版本)

CSS注入版本的优势:

  • 样式优先级更高
  • 不依赖DOM元素的存在时机
  • 对SPA页面切换更友好
  • 同时处理了CSS变量和直接的background-color

试试CSS注入版本,应该就能解决问题了!