开发者

Get CSS setting in JavaScript

Suppose I have a table in a web page:

<table><th id='th1'></th></开发者_JAVA技巧table>

Then I define the CSS in the header:

#th1
{width: 100%;}

The question is, how to get the CSS width using JavaScript? I tried width, style.width, and jQuery("#th1").css("width"), but neither of them give me the result of '100%'.


I think there's no way to get the percentage value you specified in your CSS file for your element width.

A solution would be to calculate it like this :

HTML:

<h1 id="header">Hello, World</h1>

Javascript (jQuery):

var percentageWidth = (($("#header").width()*100)/$("#header").parent().width())+"px";


Just in case, if you want to get the actual current width in pixels, not what the CSS width says, you can do:

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


<h1 id="myHeader">Text</h1>

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

Should work every time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜