如何使用jQuery从“div”标签的CSS获取值?

时间:2010-08-20 10:20:15

标签: javascript jquery html

前:

<div id="h" style="background-image:url('images//line.jpg'); background-repeat: repeat-x; width:300px; height:25px; padding-left:10px; color:white;">Frame</div>

现在,我想使用jQuery从样式中获取width的值。什么应该是jQuery。

5 个答案:

答案 0 :(得分:3)

$('#h').width()   //  from jQuery dimensions (core)

$('#h').css('width');

.width()返回计算的宽度。 .css('width')只返回您写入样式的内容。所以一般来说,坚持使用.width()是个更好的主意,除非你真的想知道实际价值。

如果您需要更多“详细信息”中元素的宽度,请查看jQuery维度中的.innerWidth().outerWidth()方法。这些人使用paddingborderspadding等计算宽度。

参考:.width().css().outerWidth().innerWidth()

答案 1 :(得分:1)

使用css方法:

$("#h").css("width");

使用css方法和width属性名称将为您提供实际的css结果,与width()相对应,这将产生无单位的结果。

来自width文档:

  

.css(宽度)和.css之间的差异   .width()是后者返回的   无单位像素值(例如,   400)而前者返回一个值   单位完好无损(例如,400px)。

答案 2 :(得分:0)

使用

$('#h').width();

$('#h').css('width');

后者返回单位值(例如300px),前者只返回值(300)。

请参阅jQuery Width() API

答案 3 :(得分:0)

css方法:

var width = $('#h').css('width');

答案 4 :(得分:0)

您可以像这样使用jQuery:

alert($("#h").css("width"));

要使用jQuery玩一点,你应该使用...

<强> http://jsfiddle.net/WEWVp/

相关问题