Javascript:如何检查样式是否已经注入

时间:2012-06-06 09:34:56

标签: javascript google-chrome-extension

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

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

但是当样式标记已经在页面中时,if不起作用。我怎样才能找到我的特定风格?

感谢。

3 个答案:

答案 0 :(得分:2)

确保在全局范围或任何外部范围内为此检查声明styleLeft。否则,你只需将它扔到示波器的末尾,并在每次迭代时创建一个新的空变量。

答案 1 :(得分: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; }";
}

答案 2 :(得分: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属性。您可以使用它来查看它是否是您的一个。