2012-04-25 7 views
12

を適用しました10pxtopプロパティに!important属性が適用されているかどうかをjQueryまたはJavaScriptを使用して確認できますか?チェックは重要な属性は

+0

?興味があるかもしれません:http://www.quirksmode.org/dom/tests/cssMisc.html。しかし、jQueryソリューションではありません。 –

答えて

8

まず、このような解決策は、jQueryの中に存在していないようです。

利用可能な多くの利用可能なjavascriptソリューションは、getPropertyPriority()関数を使用します。まず、この機能はIE6-IE8ではサポートされていません(hereおよびhereを参照)。次に、スタイルが宣言されていない場合、この関数は要素に直接作用しませんインライン。だから、私たちは、次のような場合での重要な特性を得ることができるだろう:私たちは、CSSスタイルシートで#testdivのスタイルを宣言することができれば

<div id="testdiv" style="top : 10px !important;">Some div</div> 
<script type="text/javascript"> 
// should show 'important' in the console. 
console.log(document.getElementById("testdiv").style.getPropertyPriority('top')); 
</script> 

しかし、私たちは、空の文字列を取得します。また、CSSStyleDeclarationインターフェイスはIE6-8では使用できません。もちろん、これはこの方法ではかなり役に立たない。我々は別のアプローチが必要です。

私はこのアプローチをJSFiddleに入れました。 !重要なプロパティは、配列document.styleSheets[]に含まれるcssスタイルシートから直接読み取ることができます。 (Opera 8以降はこの配列をサポートしていません)。 Quirksmodeには、スタイルシートにアクセスするためにサポートされているメソッドが表示されます。私たちは、次の操作を行うことができ、この情報に基づいて:

  • IE6-8のために、我々は、インポートされたスタイルシートにアクセスする(と私たちはもはや任意のimport文を見つけることができませんまで、再帰的にこれをやっておく)するstyleSheets[].importsを使用して、基本的にstyleSheets[].rules各スタイルシートに対して、CSSルールを配列に追加します。
  • 他のブラウザでは、styleSheets[].cssRulesを使用して、インポートされたルールとCSSルールの両方にアクセスします。 CSSImportRuleインターフェイスを実装しているかどうかを確認してインポートルールを検出し、インポートされたスタイルシートのCSSルールに再帰的にアクセスするためにこれらのルールを使用します。我々はルールが(あなたのケース#testdiv中)のHTMLElementと一致した場合にのみ、配列にCSSルールを追加し、両方のケースで

。この結果、HTMLElementにマッチするCSSルールの配列が生成されます。これは基本的にWebkitブラウザでgetMatchedCSSRules()の機能が果たす機能です。しかし、私たちはここにそれを書きます。

この情報に基づいて、hasImportant(htmlNode, property)関数を記述します。ここで、htmlNodeはHTMLElement(testdiv)で、プロパティはcssプロパティ(ケースでは「top」)です。まず、topプロパティのインラインスタイルに重要な属性があるかどうかを確認します。これにより、この属性が含まれている場合はスタイルシートを調べる手間が省けます。

私たちは良い関数node.style.getPropertyPriority(property)を使用して新しい関数isImportant(node, property)を書きます。しかし、私はこの答えの前半で述べたように、この関数はIE6-IE8ではサポートされていません。私たちは自分自身で関数を書くことができます:IEでは、プロパティnode.style.cssTextに宣言ブロック・テキストが含まれています。このテキストブロックでプロパティ( 'top')を検索し、値に '!important'が含まれているかどうかを確認します。 getMatchedCSSRules関数を使用して得られたすべてのCSSルールで、この関数をhtmlNodeと一致するすべてのCSSルールをループし、isImportant関数を呼び出すことで再利用できます。

上記のすべては、以下のコードで見つけることができます。これは、基本的なアプローチであり、おそらく、さらに微調整する必要があります。

  • いくつかのコードは、jQueryを使って交換することがあります
  • いくつかのコードは、いくつかの問題を引き起こす可能性があります
  • CSSのCSSMediaRuleインタフェースを実装ルールとother interfacesを簡素化することがあります
  • このコードのためにエラーチェックが行われなければなりません。
  • もっと簡単なアプローチかもしれませんが、私はこのクロスブラウザを得るための他の方法を知らないです。 div.style()getPropertyPriority( 'トップ'):このような

    var debug = true; 
    
    /** 
    * Get the css rules of a stylesheet which apply to the htmlNode. Meaning its class 
    * its id and its tag. 
    * @param CSSStyleSheet styleSheet 
    * @param HTMLElement htmlNode 
    */ 
    function getCssRules(styleSheet, htmlNode) { 
        if (!styleSheet) 
         return null; 
    
        var cssRules = new Array(); 
        if (styleSheet.cssRules) { 
         var currentCssRules = styleSheet.cssRules; 
         // Import statement are always at the top of the css file. 
         for (var i = 0; i < currentCssRules.length; i++) { 
          // cssRules all contains the import statements. 
          // check if the rule is an import rule. 
          if (isImportRule(currentCssRules[i])) { 
           // import the rules from the imported css file. 
           var importCssRules = getCssRules(currentCssRules[i].styleSheet, htmlNode); 
           if (importCssRules != null) { 
            // Add the rules from the import css file to the list of css rules. 
            cssRules = addToArray(cssRules, importCssRules, htmlNode); 
           } 
           // Remove the import css rule from the css rules. 
           styleSheet.deleteRule(i); 
          } 
          else { 
           // We found a rule that is not an CSSImportRule 
           break; 
          } 
         } 
         // After adding the import rules (lower priority than those in the current stylesheet), 
         // add the rules in the current stylesheet. 
         cssRules = addToArray(cssRules, currentCssRules, htmlNode); 
        } 
        else if (styleSheet.rules) { 
         // IE6-8 
         // rules do not contain the import statements. 
         var currentCssRules = styleSheet.rules; 
    
         // Handle the imports in a styleSheet file. 
         if (styleSheet.imports) { 
          // IE6-8 use a seperate array which contains the imported css files. 
          var imports = styleSheet.imports; 
          for (var i = 0; i < imports.length; i++) { 
           var importCssRules = getCssRules(imports[i], htmlNode); 
           if (importCssRules != null) { 
            // Add the rules from the import css file to the list of css rules. 
            cssRules = addToArray(cssRules, importCssRules, htmlNode); 
           } 
          } 
         } 
         // After adding the import rules (lower priority than those in the current stylesheet), 
         // add the rules in the current stylesheet. 
         cssRules = addToArray(cssRules, currentCssRules, htmlNode); 
        } 
    
        return cssRules; 
    } 
    
    /** 
    * Since a list of rules is returned, we cannot use concat. 
    * Just use old good push.... 
    * @param CSSRuleList cssRules 
    * @param CSSRuleList cssRules 
    * @param HTMLElement htmlNode 
    */ 
    function addToArray(cssRules, newRules, htmlNode) { 
        for (var i = 0; i < newRules.length; i++) { 
         if (htmlNode != undefined && htmlNode != null && isMatchCssRule(htmlNode, newRules[i])) 
          cssRules.push(newRules[i]); 
        } 
        return cssRules; 
    } 
    
    /** 
    * Matches a htmlNode to a cssRule. If it matches, return true. 
    * @param HTMLElement htmlNode 
    * @param CSSRule cssRule 
    */ 
    function isMatchCssRule(htmlNode, cssRule) { 
        // Simply use jQuery here to see if there cssRule matches the htmlNode... 
        return $(htmlNode).is(cssRule.selectorText); 
    } 
    
    /** 
    * Verifies if the cssRule implements the interface of type CSSImportRule. 
    * @param CSSRule cssRule 
    */ 
    function isImportRule(cssRule) { 
        return cssRule.constructor.toString().search("CSSImportRule") != -1; 
    } 
    
    /** 
    * Webkit browsers contain this function, but other browsers do not (yet). 
    * Implement it ourselves... 
    * 
    * Finds all matching CSS rules for the htmlNode. 
    * @param HTMLElement htmlNode 
    */ 
    function getMatchedCSSRules(htmlNode) { 
        var cssRules = new Array(); 
    
        // Opera 8- don't support styleSheets[] array. 
        if (!document.styleSheets) 
         return null; 
    
        // Loop through the stylesheets in the html document. 
        for (var i = 0; i < document.styleSheets.length; i++) { 
         var currentCssRules = getCssRules(document.styleSheets[i], htmlNode) 
         if (currentCssRules != null) 
          cssRules.push.apply(cssRules, currentCssRules); 
        } 
    
        return cssRules; 
    } 
    
    /** 
    * Checks if the CSSStyleRule has the property with 'important' attribute. 
    * @param CSSStyleRule node 
    * @param String property 
    */ 
    function isImportant(node, property) { 
        if (node.style.getPropertyPriority && node.style.getPropertyPriority(property) == 'important') 
         return true; 
        else if (node.style.cssText && getPropertyPriority(node.style.cssText, property) == 'important') { 
         // IE6-8 
         // IE thinks that cssText is part of rule.style 
         return true; 
        } 
    } 
    
    /** 
    * getPropertyPriority function for IE6-8 
    * @param String cssText 
    * @param String property 
    */ 
    function getPropertyPriority(cssText, property) { 
        var props = cssText.split(";"); 
        for (var i = 0; i < props.length; i++) { 
         if (props[i].toLowerCase().indexOf(property.toLowerCase()) != -1) { 
          // Found the correct property 
          if (props[i].toLowerCase().indexOf("!important") != -1 || props[i].toLowerCase().indexOf("! important") != -1) { 
           // IE automaticaly adds a space between ! and important... 
           return 'important'; // We found the important property for the property, return 'important'. 
          } 
         } 
        } 
        return ''; // We did not found the css property with important attribute. 
    } 
    
    /** 
    * Outputs a debug message if debugging is enabled. 
    * @param String msg 
    */ 
    function debugMsg(msg) { 
        if (debug) { 
         // For debugging purposes. 
         if (window.console) 
          console.log(msg); 
         else 
          alert(msg); 
        } 
    } 
    
    /** 
    * The main functionality required, to check whether a certain property of 
    * some html element has the important attribute. 
    * 
    * @param HTMLElement htmlNode 
    * @param String property 
    */ 
    function hasImportant(htmlNode, property) { 
    
        // First check inline style for important. 
        if (isImportant(htmlNode, property)) { 
         // For debugging purposes. 
         debugMsg("Inline contains important!"); 
         return true; 
        } 
    
        var rules = getMatchedCSSRules(htmlNode); 
    
        if (rules == null) { 
         debugMsg("This browser does not support styleSheets..."); 
         return false; 
        } 
    
        /** 
        * Iterate through the rules backwards, since rules are 
        * ordered by priority where the highest priority is last. 
        */ 
        for (var i = rules.length; i-- > 0;) { 
         var rule = rules[i]; 
    
         if (isImportant(rule, property)) { 
          // For debugging purposes. 
          debugMsg("Css contains important!"); 
          return true; 
         } 
    
        } 
        return false; 
    } 
    
    $(document).ready(function() { 
        hasImportant($('#testdiv')[0], 'top'); 
    }); 
    
+0

nice @dennisg +1 –

6

How to apply !important using .css()?

を参照してください関数は、jQueryのに追加できることがあります。あなたはこのようにそれを使用その後:すべての

console.log($('#testdiv').style().getPropertyPriority('top'));

+1

これは私にとっては機能しません。http://jsfiddle.net/74MCx/を参照してください。この関数は、関数のsetメソッドでCSS値を設定しても、CSSで宣言されたスタイルでは機能しません(空の文字列が返されます)。 – ipr101

+0

@dennisgと同様に、要素上のインライン設定のスタイルでのみ動作します。(すなわち、

Hello
) – Tobbe

関連する問題