Home  >  Article  >  Web Front-end  >  jquery如何判断某元素是否具备指定的样式_jquery

jquery如何判断某元素是否具备指定的样式_jquery

WBOY
WBOYOriginal
2016-05-16 17:17:231432browse

分为以下2种情况:
1.如果css写成行内样式,可以通过获取style属性的值来判断,示例如下:
判断id为divid的div元素是否有font-size样式:

复制代码 代码如下:


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

注:如果id为divid的div元素只有一个,则jquery的each只执行一次。
2.如果css写成类样式,可以通过获取class属性的值来判断,示例如下:
判断id为divid的div元素是否含有类样式divclass:
复制代码 代码如下:

.divclass{
background-color: #F33;
}


jquery代码如下:
复制代码 代码如下:

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

注:以上代码可以实现点击切换背景颜色。
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