开发者

How to set width and height dynamically using jQuery

I would like开发者_开发问答 to set the width and the height of the div element dynamically using jQuery.

I was trying to replace

<div id="mainTable" style="width:100px; height:200px;"></div>

with this:

$("#mainTable").css("width", "100");
$("#mainTable").css("height", "200");

but, it does not work for me.

Please help to understand why.

Thank you all !

The problem was with the quotation marks on numbers. This works fine:

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);


You can do this:

$(function() {
  $("#mainTable").width(100).height(200);
});

This has 2 changes, it now uses .width() and .height(), as well as runs the code on the document.ready event.

Without the $(function() { }) wrapper (or $(document).ready(function() { }) if you prefer), your element may not be present yet, so $("#mainTable") just wouldn't find anything to...well, do stuff to. You can see a working example here.


As @Misha Moroshko has already posted himself, this works:

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

There's some advantage to this technique over @Nick Craver's accepted answer - you can also specifiy different units:

$("#mainTable").css("width", "100%");

So @Nick Craver's method might actually be the wrong choice for some users. From the jquery API (http://api.jquery.com/width/):

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). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.


I tried below code its worked for fine

var modWidth = 250;
var modHeight = 150;

example below :-

$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);


Try this:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;


or use this syntax:

$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");


I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.

The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."

The css approach did the same thing so I had to use the $().attr() methods instead.

_canvas.attr('width', 100);
_canvas.attr('height', 200);

I don't know is this affect me because I was trying to resize a element and it is some how different or not.


$("#mainTable").css("width", "200px");
$("#mainTable").css("height", "2000px");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜