Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Properties ของ window.screen Object ใน JavaScript

Object window.screen (หรือ screen) ให้ข้อมูลเกี่ยวกับหน้าจอของผู้ใช้ นี่คือ Properties หลัก:

Propertyความหมายค่าตัวอย่าง
screen.widthความกว้างหน้าจอ (px)1920
screen.heightความสูงหน้าจอ (px)1080
screen.availWidthความกว้างพื้นที่ใช้งาน (ลบ Taskbar/Dock)1920
screen.availHeightความสูงพื้นที่ใช้งาน (ลบ Taskbar/Dock)1040
screen.colorDepthBit ต่อสี (Color Depth)24
screen.pixelDepthBit ต่อ Pixel (รวม Alpha)24
screen.orientationScreen Orientation API (ใหม่){angle: 0, type: "landscape-primary"}

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write("Screen width: " + screen.width);
      document.write("<br>Screen height: " + screen.height);
      document.write("<br>Available Screen width: " + screen.availWidth);
      document.write("<br>Available Screen height: " + screen.availHeight);
    </script>
  </body>
</html>

การใช้งานจริง

  • Responsive Design: ปรับ Layout ตาม screen.width (แต่ควรใช้ window.innerWidth / Media Queries)
  • Fullscreen App: คำนวณขนาด Canvas/Game ใช้ availWidth/Height
  • Analytics: บันทึก Screen Resolution ของ Visitor
  • PWA: ตรวจสอบ Orientation สำหรับ Install Prompt

ข้อควรระวัง: screen.width ไม่เปลี่ยนเมื่อ Zoom Browser ใช้ window.innerWidth สำหรับ Layout จริง