簡體   English   中英

JavaScript:檢查css規則是否應用於元素

[英]JavaScript: check if a css rule is applied to an element

有沒有辦法找出css規則(字符串)是否應用於頁面上的特定元素? 例如:

HTML:

<ul class="list">
  <li>List item</li>
  <li id="item">I want to check this element</li>
</ul>

CSS:

.list > li { color: red; }

JS:

var item = document.getElementById('item');
var rule = '.list > li';
isRuleApplied(rule, item);

function isRuleApplied(rule, item) {
    // ???
    // returns true if rule matches the item, false otherwise
}

[編輯]在WebKit / Blink中使用了一個特殊的函數,它返回了元素的所有匹配規則 - window.getMatchedCSSRules(node) - 但它已被棄用,不再有效。

有沒有比循環遍歷所有選擇器並檢查它們是否與元素匹配更好的方法? 此外,這種方式仍然不允許您檢查:輕松懸停狀態等。

您可以使用Element.matches || Element.matchesSelector

使用Polyfill調整MDN參考 (用於跨瀏覽器支持):

  function isRuleApplied(element,selector) {

      if(typeof element.matches == 'function')
           return element.matches(selector);

      if(typeof element.matchesSelector == 'function')
           return element.matchesSelector(selector);

      var matches = (element.document || element.ownerDocument).querySelectorAll(selector);
      var i = 0;

      while (matches[i] && matches[i] !== element)
        i++;

     return matches[i] ? true : false;
}

您可以使用document.querySelectorAll查找與規則匹配的所有元素,然后檢查結果是否包含所需元素:

 function isRuleApplied(rule, element) { var elements = document.querySelectorAll(rule), i; for (i = 0; i < elements.length; i++) { if (elements[i] === element) { return true; } } return false; } console.log(isRuleApplied(".list > li", document.getElementById("item1"))); // true console.log(isRuleApplied(".list > li", document.getElementById("item2"))); // false 
 <ul class="list"> <li id="item1">Match this</li> </ul> <ul class="test"> <li id="item2">But not this</li> </ul> 

您可以使用document.querySelectorAll(rule)來獲取與您的選擇器匹配的所有元素,然后檢查您的元素是否在那里:

function isRuleApplied(r, i) {
    var all = document.querySelectorAll(rule);
    for (var j = 0; j < all.length; j++) {
        if (all[j] == i) {
            return true;
        }
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM