คุณสมบัติความกว้างของสไตล์ HTML DOM ส่งกลับและแก้ไขคุณสมบัติความกว้าง CSS ขององค์ประกอบในเอกสาร HTML
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
-
กลับความกว้าง
object.style.width
-
ปรับเปลี่ยนความกว้าง
object.style.width = “value”
ตัวอย่าง
ให้เราดูตัวอย่างคุณสมบัติความกว้างของสไตล์ -
<!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> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

คลิกที่ “เปลี่ยนความกว้าง ” เพื่อเปลี่ยนความกว้างขององค์ประกอบย่อหน้า -
