Design

Design
asp.net mvc

2019年3月1日 星期五

取得Eelement的Css Selectors

有時候我們架構繁雜我們的css可能不像現在有前端這些framework整理好我的css
透過簡單的code去查詢我們element身上的css selectors,邏輯大致上是透過我們的document.styleSheets再去跟物件本身做逐一比對,最後可以列印出我們這個element身上有綁哪些css selectors

HTML:

  <ul>
     <li class="myclass" id="myli">Hello</li>
  </ul>
CSS:
.myclass{
   color:red;       
}
li.myclass{
   background-color:black;
}
ul li{
   float:left;
}

a{
   float:left;
}


Script:
function css(a) {
    var sheets = document.styleSheets, o = [];
    a.matches = a.matches || a.webkitMatchesSelector || a.mozMatchesSelector || a.msMatchesSelector || a.oMatchesSelector;
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.matches(rules[r].selectorText)) {
              console.log(rules[r])
                o.push(rules[r].selectorText);
            }
        }
    }
    return o;
}

document.addEventListener('click',function(e) {
console.log(css(e.target));

})

console.log(css(document.getElementById('myli')));

1 則留言:

  1. The 3 Best Hotels in Las Vegas - MapYRO
    Looking for hotels near The 3 Best Hotels in Las Vegas? MapYRO 파주 출장샵 has 1 hotels 성남 출장샵 and 3 춘천 출장안마 hotels near The 3 Best Hotels in Las 김제 출장마사지 Vegas, 서귀포 출장샵 Nevada,

    回覆刪除