如何使用jQuery动态设置宽度和高度 [英] How to set width and height dynamically using jQuery

查看:721
本文介绍了如何使用jQuery动态设置宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery动态设置 div 元素的宽度和高度。



I试图取代

 < div id =mainTablestyle =width:100px; height:200px;> < / DIV> 

用这个:

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

但它不适用于我。




$ b

谢谢大家!

问题在于数字上的引号。这工作正常:

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


解决方案

您可以这样做:

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

这有两个变化,它现在使用 .width() .height() ,以及在 document.ready 事件。


$ b

如果没有 $(function(){})包装器(或 $(document ).ready(function(){})),您的元素可能不存在,所以 $(#mainTable)只是不会找到任何东西......好吧,做点什么吧。 你可以在这里看到一个有效的例子


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.

这篇关于如何使用jQuery动态设置宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆