HTML DOM style width 属性
htmlweb developmentfront end technology更新于 2025/6/9 3:56:17
HTML DOM style width 属性用于返回并修改 HTML 文档中元素的 CSS width 属性。
语法
以下是语法 −
返回宽度
object.style.width
修改宽度
object.style.width = “value”
示例
让我们看一个样式 width 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #000;
background: lightblue;
height: 100vh;
}
p {
border: 2px solid #fff;
margin: 1.5rem auto;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>DOM Style width Property Example</h1>
<p>
This is paragraph 1 with some dummy text.
This is paragraph 1 with some dummy text.
This is paragraph 1 with some dummy text.
</p>
<button onclick="add()" class="btn">Change Width</button>
<script>
function add() {
document.querySelector('p').style.width = "50%";
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"更改宽度"按钮来更改段落元素的宽度 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

