简体   繁体   English

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

[英]How to get the value from css of “div” tag using jQuery?

Ex: 例如:

<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>

Now, I want to get the value of width from style using jQuery. 现在,我想使用jQuery从style中获取width的值。 What should be jQuery. jQuery应该是什么。

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

or 要么

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

.width() returns the calculated width. .width()返回计算出的宽度。 .css('width') just returns whatever you've written into the style. .css('width')只会返回您已写入样式的内容。 So in general, it's a better idea to stick with .width() unless you really want to know the actuall value. 因此,通常来说,最好使用.width()除非您真的想知道实际值。

If you need the width of an element in more "detail", check out the .innerWidth() and .outerWidth() methods from jQuery dimensions. 如果您需要元素的宽度更“详细”,请从jQuery尺寸中.innerWidth().outerWidth()方法。 Those calculate the width with padding , borders , padding etc. 这些使用paddingborderspadding等计算宽度。

Ref.: .width() , .css() , .outerWidth() , .innerWidth() 编号: .WIDTH() , 的.css() , .outerWidth() , .innerWidth()

Use the css method: 使用css方法:

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

Using the css method and the property name of width will give you the actual css result, as apposed to width() which will give a unitless result. 使用css方法和width的属性名称将为您提供实际的css结果,如与width()并排的将给出无单位的结果。

From the width docs: 宽度文档:

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). .css(width)和.width()之间的区别在于,后者返回无单位像素值(例如400),而前者返回完整单位的值(例如400px)。

Use either 使用任一

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

or 要么

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

The latter returns the unit value (eg 300px), the former just a value (300). 后者返回单位值(例如300px),前者只是一个值(300)。

See jQuery Width() API 参见jQuery Width()API

css方法:

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

You could use jQuery like this: 您可以像这样使用jQuery:

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

To play a little with jQuery you should use... 要使用jQuery,请使用...

http://jsfiddle.net/WEWVp/ http://jsfiddle.net/WEWVp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM