Javascript 在标准模式下设置元素宽度或高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4667651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set element width or height in Standards Mode
提问by rafalry
Is it possible to set width or height of HTML element (ex. <div>
) in JavaScript in Standards Mode?
是否可以<div>
在标准模式下在 JavaScript 中设置 HTML 元素(例如)的宽度或高度?
Note the following code:
请注意以下代码:
<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>
When user presses the change widthbutton, the <div>
's width should change.
当用户按下更改宽度按钮时,<div>
的宽度应更改。
It works fine when doctype declaration determines Quirks Mode. In Standards Mode I'm unable to change the element's size this way
当 doctype 声明确定 Quirks 模式时,它工作正常。在标准模式下,我无法以这种方式更改元素的大小
Is it possible to manipulate the size of an element in Standards Mode? How to bypass this disfunctionality?
是否可以在标准模式下操纵元素的大小?如何绕过这种功能障碍?
回答by Alexandre Perez
Try declaring the unit of width:
尝试声明宽度单位:
e1.style.width = "400px"; // width in PIXELS
回答by Quentin
The style
property lets you specify values for CSS properties.
该style
属性允许您为 CSS 属性指定值。
The CSS width
property takes a length as its value.
CSSwidth
属性将长度作为其值。
Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.
长度需要单位。在 quirks 模式下,如果提供整数而不是长度,浏览器倾向于假设像素。指定单位。
e1.style.width = "400px";