jquery 判断某元素是否定义了 CSS

HTML:
<p class="acont"><a >我是一匹来自北方的狼</a></p>

CSS:
p.acont a{float:left; font-size:12px;} /*注意此处没有定义margin-right*/

JQUERY:
alert($(".acont a").css("margin-right")); //返回“0px”

疑问:
.acont a在CSS中并没有定义“margin-right”属性,为什么jquery会返回0px呢?
我的目的:
在jquery中判断.acont a是否定义了“margin-right”属性,如果有的话,其值不变,如果没有的话,指定一个“margin-right”属性的值。

有劳了。
可能我没有表达明白,用下面的表格表达可能更明白些。

应该可以看出,判断CSS中是否定义跟0px还是有区别的。

这个js、jq都没办法判断是否定义某个css,
这里可以提供两个解决思路:1、有人已经说了判断值是否等于0;但是这样一来会有个弊端,如果css中确实定义了margin-right:0;也会把它当做未定义处理;
2、把css写成行内样式<a style="float:left; font-size:12px;">的</a>,这样可以获取style的值再判断是否有margin-right;
$(".acont a").each(function(){
var ofright = $(this).attr("style").indexOf("margin-right");
if(ofright != (-1)){alert("已定义");}
else{$(this).css({"float":"left","font-size":"12px","margin-left":"10px"});}
});
如果只有一个就不需要循环了

好吧,再给你个思路,
在css中这么定义
.mr{margin-right:5px;}
p.acont a{float:left; font-size:12px;}
HTML中这么写:
<p class="acont"><a class="mr">我是一匹来自北方的狼</a></p>
这个思路是通过相同样式冲突覆盖来解决的
p.acont a中如果定义了margin-right就会覆盖.mr中的margin-right:5px;,使之不起作用
如果未定义.mr{margin-right:5px;}这个就会起作用
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-01-09
$("#div").attr("class")得到class的值,判断这个值是否为空。
第2个回答  2013-01-09
没有定义margin-right,所以取默认值为0,
可以判断一下
if(parseInt($(".acont a").css("margin-left")) == 0){
$(".acont a").css("margin-left","10px");
}
相似回答