window.innerWidth ความกว้าง Viewport (Content Area) | window.innerHeight ความสูง Viewport
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Window Dimensions</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Window innerWidth and innerHeight</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to get viewport dimensions </h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = "innerWidth = " + window.innerWidth + "<br>";
resEle.innerHTML += "innerHeight = " + window.innerHeight + "<br>";
resEle.innerHTML += "outerWidth = " + window.outerWidth + "<br>";
resEle.innerHTML += "outerHeight = " + window.outerHeight;
});
</script>
</body>
</html>
คำอธิบาย
- innerWidth/Height: Viewport (เนื้อหาเว็บ) ไม่รวม Scrollbar, Toolbar
- outerWidth/Height: หน้าต่าง Browser ทั้งหมด รวม UI
- screen.width/height: จอภาพ Physical
- document.documentElement.clientWidth/Height: เท่ากับ inner แต่ไม่รวม Scrollbar
- Event:
window.addEventListener('resize', handler)ติดตามการ Resize
ผลลัพธ์
แสดงตัวเลขพิกเซล เช่น innerWidth=1920, innerHeight=937 (ขึ้นอยู่กับขนาดหน้าต่าง)