0){...}else"."/> 0){...}else".">

Home  >  Article  >  Web Front-end  >  How to check if an object has a certain style with jquery

How to check if an object has a certain style with jquery

WBOY
WBOYOriginal
2022-06-13 17:14:312311browse

Method: 1. If the style is an inline style, you can use the value of the style attribute to judge. The syntax is "var a = $(this).attr("style").indexOf("attribute"); if(a != (-1)){...}else{...}"; 2. If the style is a class style, you can use class to judge, and the syntax is "if(element object.attr("class") .indexOf("divclass")>0){...}else".

How to check if an object has a certain style with jquery

The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.

How does jquery check whether an object has a certain style

1. If the css is written as an inline style, it can be judged by getting the value of the style attribute. The example is as follows:

Determine whether the div element with id divid has a font-size style:

<div id="divid" style="float:left; font-size:12px;"></div>

jquery code is as follows:

jQuery("#divid").each(function(){
  var fontSize = $(this).attr("style").indexOf("font-size");
  if(fontSize != (-1)){alert("已定义");}
  else{$(this).css({"float":"left","font-size":"12px"});}
});

Note: If there is only one div element with id divid, then jquery Each is executed only once.

2. If the css is written as a class style, it can be judged by getting the value of the class attribute. The example is as follows:

Judge whether the div element with the id of divid contains the class style divclass:

.divclass{
background-color: #F33;
}
<div id="divid" class="divclass"></div>

jquery code is as follows:

jQuery("#divid").click(function(){
if(jQuery(this).attr("class").indexOf("divclass")>0){
    jQuery(this).removeClass("divclass")
}else{
    jQuery(this).addClass("divclass")
}
});

Video tutorial recommendation: jQuery video tutorial

The above is the detailed content of How to check if an object has a certain style with jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn