是否有与 GreaseMonkey 相当的 TamperMonkeyGM_addStyle
添加CSS的方法?
在 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";
已弃用
If 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; }");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)