【问题标题】:Set element width or height in Standards Mode在标准模式下设置元素宽度或高度
【发布时间】:2011-06-07 17:57:08
【问题描述】:

是否可以在标准模式下的 JavaScript 中设置 HTML 元素的宽度或高度(例如 <div>)?

注意以下代码:

<html>
<script language="javascript" type="text/javascript">
    function changeWidth(){
        var e1 = document.getElementById("e1");
        e1.style.width = 400;
    } 
</script>
<body>
    <input type="button" value="change width" onclick="changeWidth()"/>
    <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</body>
</html>

当用户按下改变宽度按钮时,&lt;div&gt;的宽度应该改变。

当 doctype 声明确定 Quirks 模式时,它可以正常工作。在标准模式下,我无法以这种方式更改元素的大小

是否可以在标准模式下控制元素的大小?如何绕过这个功能障碍?

【问题讨论】:

    标签: javascript size standards element quirks-mode


    【解决方案1】:

    尝试声明宽度单位:

    e1.style.width = "400px"; // width in PIXELS
    

    【讨论】:

    • 啊哈哈..我的意思是“喵”(c)。我花了大约一个小时,试图弄清楚为什么不应用样式。谢谢!
    • 值得一提的是宽度不包含边距,box-sizing: border-box;时宽度包含边距,否则宽度不包含边距。
    • 相当讨厌window.innerWidth 只返回一个没有附加任何单位的整数...
    【解决方案2】:

    style 属性允许您指定 CSS 属性的值。

    CSS width 属性将长度作为其值。

    长度需要单位。在 quirks 模式下,如果提供整数而不是长度,浏览器倾向于假定像素。指定单位。

    e1.style.width = "400px";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多