Javascript 如何检查样式是否已追加

Javascript 如何检查样式是否已追加,javascript,jquery,css,Javascript,Jquery,Css,这是我的密码 <!DOCTYPE html> <html> <head> <style> .class1 { color:red; } </style> </head> <body> <h1>This is a heading</h1> </body> </html> .1级{ 颜色:红色; } 这是一个标题 我需要检查class1是否在jquery中使用

这是我的密码

<!DOCTYPE html>
<html>
<head>
<style>
.class1 {
  color:red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>

.1级{
颜色:红色;
}
这是一个标题

我需要检查class1是否在jquery中使用或附加了in-style标记?如何可能..

我猜您想知道样式是否在样式标记中提供。只需获取所有样式标记,然后查看类是否在标记中

var found_class = false;
$('style').each(function() {
   if ($(this).html().indexOf('.class1') > -1) {
      found_class = true;
      return false;
   }
});
试试这个:

if ($(".class1")[0]){
    //exists
} else {
    // Do something if class does not exist
}


您可以使用have.hasClass()在jquery中检查它。该方法返回truefalse关于是否包含所需的类。

我不知道使用jQuery是否可以轻松实现这一点,但这里有一种“普通”JavaScript方法来实现

样式表有一个
cssRules
属性,该属性包含其规则的列表,按它们在样式表中出现的索引排序。因此,基本上,您可以“循环”规则,并尝试找到一个与您的搜索匹配的规则

功能:

function ruleExists(sheetId, selector) {
    var styleSheet = document.getElementById(sheetId);
    if(!styleSheet || styleSheet.tagName !== 'STYLE') return false;
    styleSheet = styleSheet.sheet.cssRules;
    for (var i = styleSheet.length; i--;) {
        if(styleSheet[i].selectorText === selector) return true;
    }
    return false;
}
<style type="text/css" id="styleShizz">
    .class1 {
        color: red;
    }
</style>
ruleExists('styleShizz', '.class1'); // true
ruleExists('styleShizz', '.class2'); // false
因此,只需在样式表中添加一个
id
(我发现这比使用document.styleSheets更方便,但您可以修改函数以使用它),然后将样式表的id和所需的规则选择器传递给函数。(当然,如果您使用的是ids,那么这只适用于内联样式表)。下面是一个例子:

您的样式表:

function ruleExists(sheetId, selector) {
    var styleSheet = document.getElementById(sheetId);
    if(!styleSheet || styleSheet.tagName !== 'STYLE') return false;
    styleSheet = styleSheet.sheet.cssRules;
    for (var i = styleSheet.length; i--;) {
        if(styleSheet[i].selectorText === selector) return true;
    }
    return false;
}
<style type="text/css" id="styleShizz">
    .class1 {
        color: red;
    }
</style>
ruleExists('styleShizz', '.class1'); // true
ruleExists('styleShizz', '.class2'); // false

下面是一个JSFIDLE示例:

function ruleExists(sheetId, selector) {
    var styleSheet = document.getElementById(sheetId);
    if(!styleSheet || styleSheet.tagName !== 'STYLE') return false;
    styleSheet = styleSheet.sheet.cssRules;
    for (var i = styleSheet.length; i--;) {
        if(styleSheet[i].selectorText === selector) return true;
    }
    return false;
}
<style type="text/css" id="styleShizz">
    .class1 {
        color: red;
    }
</style>
ruleExists('styleShizz', '.class1'); // true
ruleExists('styleShizz', '.class2'); // false

是否要检查该类是否存在?是的,这就是我需要的检查具有该类的元素的计数如何?您的问题的意思是:样式标记是否包含类“class1”,或者类“class1”是否已应用于任何html元素??请澄清您的问题。我需要检查class1样式是否存在出口