0){...}else"."/> 0){...}else".">
Home > Article > Web Front-end > How to check if an object has a certain style with jquery
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".
The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.
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!