คุณสมบัติ offsetWidth ของ HTML DOM ส่งคืน ตัวเลข ที่แสดงความกว้างขององค์ประกอบ (element) รวมถึง padding, border และ scrollbar แต่ ไม่รวม margin
ไวยากรณ์ (Syntax)
HTMLelement.offsetWidth
ตัวอย่างการใช้งาน
ตัวอย่างนี้วัดความกว้างของรูปภาพและคอนเทนเนอร์ที่มี scrollbar
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM offsetWidth</title>
<style>
form { width:70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin:5px; }
input[type="button"] { border-radius: 10px; }
#containerDiv { margin: 0 auto; height: 100px; width: 100px; overflow: auto; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>HTML-DOM-offsetWidth</legend>
<div id="containerDiv">
<img id="image" src="https://www.tutorialspoint.com/hibernate/images/hibernate-mini-logo.jpg">
</div>
<input type="button" onclick="getWidth()" value="Get width of picture">
<input type="button" onclick="fitWidth()" value="Remove Scrollbars">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var imgSelect = document.getElementById("image");
var containerDiv = document.getElementById("containerDiv");
function getWidth() {
divDisplay.innerHTML = 'Width of above picture with padding & border: '+imgSelect.offsetWidth;
divDisplay.innerHTML += '<br>Width of container with padding & border: '+containerDiv.offsetWidth;
}
function fitWidth() {
containerDiv.style.height = imgSelect.height+'px';
containerDiv.style.width = imgSelect.width+'px';
containerDiv.style.overflow = 'hidden';
getWidth();
}
</script>
</body>
</html>
ผลลัพธ์ (Output)
ก่อนกดปุ่มใดๆ:

หลังกดปุ่ม "Get Width of picture":

หลังกดปุ่ม "Remove Scrollbars":
