开发者

Querying an inline style property in JQuery

I am writing a JQuery HTML parser for some particularly formatted HTML and I need to query an inline style for a value.

Within the code I am stepping through particular input fields and saving out this particular style to an array...

First here is the code I am using to step through these input fields and grab the widths. This works but does not return the correct width value (I want the EM value).

$('.inputBox',this).each(function(index)
{
   widthArray[widthArray.length] = $(this).attr('width');
}

Here is a simplified example of one of the input boxes

<input style="width:1.9500000000000002em;" maxlength="3" tabindex="1" 开发者_Python百科class="inputBox" type="text">

Any help appreciated. Thanks!


Of course the easiest way is to get it from the style attribute of this.

$('.inputBox', this).each(function(index) {
   widthArray[widthArray.length] = this.style.width;
});

Live Demo

From here on this is just drunken speculation: theoretically, you can get the style attribute and split the values found in there based on ;. Then you can further split them on : to get the key-value pairs.

Something like:

$('.inputBox', this).each(function(index) {
   var stylestemp = $(this).attr('style').split(';');
   var styles = {};
   var c = '';
   for (var x = 0, l = stylestemp.length; x < l; x++) {
     c = stylestemp[x].split(':');
     styles[$.trim(c[0])] = $.trim(c[1]);
   }
   widthArray[widthArray.length] = styles.width;
});

Live Demo of Drunken Speculation


unfortunatelly jquery actually serves only px-values - it's the same with the width() method, b.t.w.

A little dirty, but if "width" is the only style-element of your inputs, you could retrieve the whole style string and parse it by yourself:

var inputStyle = $("input").attr('style');
// make an array [ 'width', '1.9500000000000002em;' ]
var styleParts = inputStyle.split(':');
// make float from 1.9500000000000002em; --> 1.95
var widthEm = parseFloat(styleParts[1]);

Due to float precision in javascript you'll lose your ...0000002 at the end. Maybe you'll need to parse the number with string methods.


Because you checking the attrubute instead of the style width

$(this).css('width')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜