簡體   English   中英

如何確定 Javascript 是否存在 css 類?

[英]How can you determine if a css class exists with Javascript?

有沒有辦法使用 JavaScript 確定 css 類是否存在?

這應該可以使用document.styleSheets[].rules[].selectorTextdocument.styleSheets[].imports[].rules[].selectorText屬性來完成。 請參閱MDN 文檔

function getAllSelectors() { 
    var ret = [];
    for(var i = 0; i < document.styleSheets.length; i++) {
        var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
        for(var x in rules) {
            if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
        }
    }
    return ret;
}


function selectorExists(selector) { 
    var selectors = getAllSelectors();
    for(var i = 0; i < selectors.length; i++) {
        if(selectors[i] == selector) return true;
    }
    return false;
}

這是我對此的解決方案。 我基本上只是像@helen 建議的那樣循環遍歷 document.styleSheets[].rules[].selectorText。

/**
 * This function searches for the existence of a specified CSS selector in a given stylesheet.
 *
 * @param (string) styleSheetName - This is the name of the stylesheet you'd like to search
 * @param (string) selector - This is the name of the selector you'd like to find
 * @return (bool) - Returns true if the selector is found, false if it's not found
 * @example - console.log(selectorInStyleSheet ('myStyleSheet.css', '.myClass'));
 */    

function selectorInStyleSheet(styleSheetName, selector) {
    /*
     * Get the index of 'styleSheetName' from the document.styleSheets object
     */
    for (var i = 0; i < document.styleSheets.length; i++) {
        var thisStyleSheet = document.styleSheets[i].href ? document.styleSheets[i].href.replace(/^.*[\\\/]/, '') : '';
        if (thisStyleSheet == styleSheetName) { var idx = i; break; }
    }
    if (!idx) return false; // We can't find the specified stylesheet

    /*
     * Check the stylesheet for the specified selector
     */
    var styleSheet = document.styleSheets[idx];
    var cssRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
    for (var i = 0; i < cssRules.length; ++i) {
        if(cssRules[i].selectorText == selector) return true;
    }
    return false;
}

與其他解決方案相比,此函數提供了速度改進,因為我們只搜索傳遞給該函數的樣式表。 其他解決方案遍歷所有樣式表,這在許多情況下是不必要的。

根據答案,我創建了一個 javascript 函數,用於在瀏覽器的內存中搜索 CSS 類 -

var searchForCss = function (searchClassName) {
  for (let i = 0; i < document.styleSheets.length; i++) {
    let styleSheet = document.styleSheets[i];
    try {
      for (let j = 0; j < styleSheet.cssRules.length; j++) {
        let rule = styleSheet.cssRules[j];
        // console.log(rule.selectorText)
        if (rule.selectorText && rule.selectorText.includes(searchClassName)) {
          console.log('found - ', rule.selectorText, ' ', i, '-', j);
        }
      }
      if (styleSheet.imports) {
        for (let k = 0; k < styleSheet.imports.length; k++) {
          let imp = styleSheet.imports[k];
          for (let l = 0; l < imp.cssRules.length; l++) {
            let rule = imp.cssRules[l];
            if (
              rule.selectorText &&
              rule.selectorText.includes(searchClassName)
            ) {
              console.log('found - ',rule.selectorText,' ',i,'-',k,'-',l);
            }
          }
        }
      }
    } catch (err) {}
  }
};

searchForCss('my-class-name');

這將在任何樣式表的任何規則中為每次出現類名打印一行。

Ref - 在瀏覽器內存中搜索 CSS 類

/* 您可以遍歷當前加載的每個樣式表,並為您指定的任何選擇器文本返回所有已定義規則的數組,從標簽名稱到類名稱或標識符。

請勿包含“#”或“.” id 或類名的前綴。

Safari 過去會跳過禁用的樣式表,可能還有其他問題,但閱讀規則在瀏覽器中通常比編寫新規則更有效。 */

function getDefinedCss(s){
    if(!document.styleSheets) return '';
    if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE capitalizes html selectors 

    var A, S, DS= document.styleSheets, n= DS.length, SA= [];
    while(n){
        S= DS[--n];
        A= (S.rules)? S.rules: S.cssRules;
        for(var i= 0, L= A.length; i<L; i++){
            tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
            if(s.test(tem[0])) SA[SA.length]= tem;
        }
    }
    return SA.join('\n\n');
}

getDefinedCss('p') //如果你願意,可以替換一個類名或ID

級聯中的最新項目首先列出。

在上面添加這個條件

if (!document.getElementsByClassName('className').length){
    //class not there
}
else{
//class there
}

如果想檢查一個元素只需使用

element.hasClassName( className );

您也可以在 ID 上使用

document.getElementById("myDIV").classList.contains('className');

祝你好運 !!!

基於海倫的回答,我想出了這個:

//**************************************************************************
//** hasStyleRule
//**************************************************************************
/** Returns true if there is a style rule defined for a given selector.
 *  @param selector CSS selector (e.g. ".deleteIcon", "h2", "#mid")
 */
  var hasStyleRule = function(selector) {

      var hasRule = function(selector, rules){
          if (!rules) return false;
          for (var i=0; i<rules.length; i++) {
              var rule = rules[i];
              if (rule.selectorText){ 
                  var arr = rule.selectorText.split(',');
                  for (var j=0; j<arr.length; j++){
                      if (arr[j].indexOf(selector) !== -1){
                          var txt = trim(arr[j]);
                          if (txt===selector){
                              return true;
                          }
                          else{
                              var colIdx = txt.indexOf(":");
                              if (colIdx !== -1){
                                  txt = trim(txt.substring(0, colIdx));
                                  if (txt===selector){
                                      return true;
                                  }
                              }
                          }
                      }
                  }
              }
          }
          return false;
      };

      var trim = function(str){
          return str.replace(/^\s*/, "").replace(/\s*$/, "");
      };

      for (var i=0; i<document.styleSheets.length; i++){
          var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
          if (hasRule(selector, rules)){
              return true;
          }

          var imports = document.styleSheets[i].imports;
          if (imports){
              for (var j=0; j<imports.length; j++){
                  rules = imports[j].rules || imports[j].cssRules;
                  if (hasRule(selector, rules)) return true;
              }
          }
      } 

      return false;
  };

可以檢查並查看您正在尋找的樣式的對象是否已經存在。 如果是,則 css 類必須存在,因為對象正在使用它。 例如,如果您想確保不同命名的 svg 對象每個都有自己的樣式:

function getClassName(name) {
    //Are there any elements which use a style named 'name' ?
    if (document.getElementsByClassName(name).length === 0){
        //There are none yest, let's make a new style and add it
        var style = document.createElement('style');
        style.type = 'text/css';
        //Where you might provide your own hash function or rnd color
        style.innerHTML = '.'+name+' { fill: #' + getHashColor(name) + '; background: #F495A3; }';
        //Add the style to the document
        document.getElementsByTagName('head')[0].appendChild(style);
        }
        return name;
    }

請注意,如果您正在尋找一種不一定在您的文檔中使用的樣式,這不是一個好方法。

if ($(".class-name").length > 0) {

}

這是使用 javascript 檢查 HTML 中的類的好方法

單線:

[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")
function getAllSelectors() {
  var ret = {};
  for(var i=0;i<document.styleSheets.length;i++){
    try {
      var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
      for(var x in rules) {
        if(typeof rules[x].selectorText === 'string'){
          if(ret[rules[x].selectorText] === undefined){
            ret[rules[x].selectorText] = rules[x].style.cssText;
          }
          else {
            ret[rules[x].selectorText] = ret[rules[x].selectorText] + ' ' + rules[x].style.cssText;
          }
        }
      }    
    }
    catch(error){
      console.log(document.styleSheets[i]);
    }
  }
  return ret;
}
function selectorExists(selector) {
  var selectors = getAllSelectors();
  if(selectors[selector] !== undefined){
    return true;
  }
  return false;
}
// var allSelectors = getAllSelectors();

暫無
暫無

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

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