如何在JavaScript中设置div的宽度百分比?

时间:2010-03-17 08:09:43

标签: javascript jquery

是否可以使用JavaScript或jQuery以百分比形式设置元素的高度/宽度?​​

7 个答案:

答案 0 :(得分:41)

document.getElementById('header').style.width = '50%';

如果您使用的是Firebug或Chrome / Safari开发人员工具,请在控制台中执行上述操作,您会看到Stack Overflow标头缩小50%。

答案 1 :(得分:33)

jQuery方式 -

$("#id").width('30%');

答案 2 :(得分:9)

我总是这样做:

$("#id").css("width", "50%");

答案 3 :(得分:3)

问题是你希望div的高度/宽度是百分之几?

默认情况下,如果您为高度/宽度指定百分比值,则它将相对于其直接父级尺寸。如果父级没有定义的高度,那么它将无法工作。

如此简单,请记住设置父级的高度,然后百分比高度将通过css属性起作用:

obj.style.width = '50%';

答案 4 :(得分:2)

是的,它是:

<div id="myid">Some Content........</div>

document.getElementById('#myid').style.width = '50%';

答案 5 :(得分:1)

此外,您可以使用 .prop() ,它应该更好,因为

  

从jQuery 1.6开始,无法再使用.attr()方法设置这些属性。它们没有相应的属性,只是属性。

$(elem).prop('width', '100%');
$(elem).prop('height', '100%');

答案 6 :(得分:0)

                    testjs2                           

    $(document).ready(function() { 
      $("#form1").validate({ 
        rules: { 
          name: "required", //simple rule, converted to {required:true} 
          email: { //compound rule 
          required: true, 
          email: true 
        }, 
        url: { 
          url: true 
        }, 
        comment: { 
          required: true 
        } 
        }, 
        messages: { 
          comment: "Please enter a comment." 
        } 
      }); 
    }); 

    function()
    {
    var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
    if (ok)
    location="http://www.yahoo.com"
    else
    location="http://www.hotmail.com"
    }

    function changeWidth(){
    var e1 = document.getElementById("e1");
    e1.style.width = 400;
} 

  </script> 

  <style type="text/css"> 
    * { font-family: Verdana; font-size: 11px; line-height: 14px; } 
    .submit { margin-left: 125px; margin-top: 10px;} 
    .label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; } 
    .form-row { padding: 5px 0; clear: both; width: 700px; } 
    .label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; } 
    .input[type=text], textarea { width: 250px; float: left; } 
    .textarea { height: 50px; } 
  </style> 

  </head> 
  <body> 

    <form id="form1" method="post" action=""> 
      <div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div> 
      <div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div> 
      <div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div> 
      <div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div> 
      <div class="form-row"><input class="submit" type="submit" value="Submit"></div> 
      <input type="button" value="change width" onclick="changeWidth()"/>
      <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
    </form> 



  </body> 
</html> 
相关问题