【问题标题】:Why isn't this function returning a css rule?为什么这个函数不返回 css 规则?
【发布时间】:2013-06-26 16:25:18
【问题描述】:

我正在尝试编写一些辅助函数,以便可以通过 javascript 编辑 css 类。这是我所拥有的,但我不明白为什么它一直返回“未定义”。我正在使用 chrome 进行测试。

    function getRule(name, doDelete) { //takes a rule name and boolean

    if(document.styleSheets) { //check if there are stylesheets

        for(var i = 0; i < document.styleSheets.length; i++) { //loop through style sheets

            var currentSheet = document.styleSheets[i];
            if(currentSheet.cssRules) { //if the sheet has rules

                for(var h = 0; h < currentSheet.cssRules.length; h++) { //loop through css rules

                    var currentRule = currentSheet.cssRules[h];
                    if(currentRule.selectorText == name) { //if rule name is equal to the name given

                        return currentRule; //return the css rule

                    }

                }

            }

        }

    }

}

正在使用的css:

    .menuopen {

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    font-size: 20px;
    width: 960px;
    height: 200px;
    background-color: 3b7ea8;
    box-shadow: inset 0px 2px 5px 3px rgba(0,0,0,0.75);
    -webkit-animation-name: dropAnimation;
    -webkit-animation-duration: 2s;

    }

【问题讨论】:

  • 您是如何搜索规则的?我刚刚做了一个小提琴,你的代码似乎有效! jsfiddle.net/kA24S/2
  • 真的吗?我在 Chrome 中使用它并输入 getRule(".dropmenu") 但它不起作用。也许它只是铬?
  • 我也在使用 Chrome。我可以看看你正在使用的 CSS 吗?
  • 最近改名为“menuopen”只是为了让您知道这不是一个错误。
  • This 可能会有所帮助

标签: javascript css google-chrome dom


【解决方案1】:

这些问题之一可能是问题吗?
document.styleSheets[n].cssRules null when page accessed locally
cssRules is null for CSSStyleSheets from other domains
Regression: cssRules null when stylesheets loaded from local disk
这些问题的出现取决于样式表的包含方式以及页面加载方式(从磁盘或服务器)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2019-09-27
    相关资源
    最近更新 更多