0

在 Chrome 插件中,通过后台脚本,我以这种方式注入样式:

if(!styleLeft){
    var styleLeft = document.createElement("style");
    document.head.appendChild(styleLeft);
    styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
}

但是当样式标签已经在页面中时 if 不起作用。如何寻找我的特定风格?

谢谢。

4

3 回答 3

2

确保您styleLeft在全局范围或任何外部范围内声明此检查。否则,您只需在范围结束时将其丢弃,并将在每次迭代时创建一个新的空变量。

于 2012-06-06T09:37:39.940 回答
1

检查身份证。例子:

if ( !!document.getElementById( 'a-long-id-that-will-never-collide' ) ) {
    var styleLeft = document.createElement("style");

    // Set the ID so that you can check for it later
    styleLeft.id = 'a-long-id-that-will-never-collide';

    document.head.appendChild(styleLeft);
    styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
}
于 2012-06-06T09:46:38.510 回答
0

您可以解析document.styleSheets(它们应该可以在 Chrome 插件中访问,但我不是 100% 确定)。如果您为注入的每个样式都赋予一个唯一的标题,您将更容易找到已注入的样式:

var styleLeft = document.createElement("style");
styleLeft.setAttribute("title", "<a unique id>");
document.head.appendChild(styleLeft);
styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
document.head.appendChild(styleLeft);

现在最后一个条目document.styleSheets有一个 .title 属性。你可以用它来看看它是否是你的。

于 2012-06-06T09:49:08.200 回答