gpt4 book ai didi

css - TamperMonkey 中的 GM_addStyle 等价物

转载 作者:技术小花猫 更新时间:2023-10-29 10:10:31 46 4
gpt4 key购买 nike

是否有与 GreaseMonkey 的 GM_addStyle 方法等效的用于添加 CSS 的 TamperMonkey?

在 GreaseMonkey 中,您可以像这样向多个元素添加一堆 CSS 属性:

GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");

要在 TamperMonkey 中执行相同的操作,我目前必须执行以下操作:

function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}

addGlobalStyle('body { color: white; background-color: black; }');

这行得通,但是是否有内置的 GM_addStyle 等同于 TamperMonkey,使我不必在每个脚本上重复此操作?

最佳答案

版本 4.0 或 +,2018 年更新

ReferenceError: GM_addStyle is not defined

您需要创建自己的 GM_addStyle 函数,如下所示:

// ==UserScript==
// @name Example
// @description Usercript with GM_addStyle method.
// ==/UserScript==

function GM_addStyle(css) {
const style = document.getElementById("GM_addStyleBy8626") || (function() {
const style = document.createElement('style');
style.type = 'text/css';
style.id = "GM_addStyleBy8626";
document.head.appendChild(style);
return style;
})();
const sheet = style.sheet;
sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}

//demo :
GM_addStyle("p { color:red; }");
GM_addStyle("p { text-decoration:underline; }");

document.body.innerHTML = "<p>I used GM_addStyle.</p><pre></pre>";

const sheet = document.getElementById("GM_addStyleBy8626").sheet,
rules = (sheet.rules || sheet.cssRules);

for (let i=0; i<rules.length; i++)
document.querySelector("pre").innerHTML += rules[i].cssText + "\n";

已弃用

如果 GM_addStyle(...) 不起作用,请检查您是否有 @grant GM_addStyle header 。

像这样:

// ==UserScript==
// @name Example
// @description See usercript with grant header.
// @grant GM_addStyle
// ==/UserScript==

GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");

关于css - TamperMonkey 中的 GM_addStyle 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683439/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com