我看到上一篇帖子类似于我的问题 HTML5 canvas style height vs attribute height
但是在那篇文章中,没有明确的信息说明哪一个会起作用,有什么区别?
我尝试了以下示例:
<html>
<head>
</head>
<body>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="jquery-1.11.1.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script src="script.js"></script>
<div>
<select style="width: 200px" width="200px">
<option value="Test1"> Test1 </option>
<option value="Test2"> Test2 </option>
<option value="Test3"> Test3</option>
<option value="Test4"> Test4 </option>
<option value="Test5"> Test5 </option>
</select>
</div>
</body>
</html>
但在上面的示例中,如果放置 style=“width: 200px” 或 width=“200px” ,则不会看到相同的结果。
问题:
为什么 style=“width: 200px 和 width=“200px 没有给出相同的结果?
width=“200px” 和 width=“200” 有什么区别?
有人可以帮助我清除这些基础知识吗?
原文由 Manku 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于大多数 html 元素,
width
属性与元素的宽度无关。定义元素样式(肯定包含width
)的是元素的style
属性。换句话说,
style.width
(style="width: 200px;"
)属性决定了元素的宽度。But some elements like
canvas
,svg
, thewidth
attribute will determines the element’s width, if you don’t setstyle.width
attribute.在这种情况下,width="200px"
与width="200"
相同,因为大多数浏览器使用px
作为默认单位。附言:
width
设置select
的宽度无效。width
属性是有效的。您可以自由访问和更改它。你可以用它来做其他事情。