如何在 JavaScript 中獲取螢幕的寬度和高度?
在本文中,我們將討論如何在 JavaScript 中獲取螢幕的寬度和高度。
Javascript 提供了一個 `window.screen` 物件,其中包含有關使用者螢幕的資訊。這些資訊包括高度和寬度,以及許多其他功能。
要查詢螢幕的高度和寬度,您需要使用以下只讀屬性:
- `screen.height` − 此屬性用於以畫素為單位獲取螢幕的高度。
- `screen.width` − 此屬性用於以畫素為單位獲取螢幕的寬度。
語法
以下是分別獲取螢幕高度和寬度的語法:
screen.height; screen.width;
示例 1
在以下示例中,使用 `screen.width` 方法顯示螢幕的寬度。
<html> <body> <p id="width"> </p> <script> document.getElementById("width").innerHTML = "Screen width is " + screen.width; </script> </body> </html>
示例 2
在以下示例中,使用 `screen.height` 方法顯示螢幕的高度。
<html> <body> <p id="height"> </p> <script> document.getElementById("height").innerHTML = "Screen heigth is " + screen.height; </script> </body> </html>
示例 3
在以下示例中,我們嘗試使用 `screen.width` 和 `screen.height` 屬性獲取螢幕的寬度和高度:
<!DOCTYPE html> <html lang="en"> <head> <title>Get the width and height of the screen</title> <div id="width"></div> <div id="height"></div> </head> <body> <script type="text/javascript"> document.getElementById("width").innerHTML ="Width of the screen : " + screen.width; document.getElementById("height").innerHTML ="Height of the screen : " + screen.height; </script> </body> </html>
示例 4
以下是另一個示例:
<!DOCTYPE html> <html lang="en"> <head> <title>Get the width and height of the screen</title> <input type="button" onclick="getWidthLength()" value="click here to get the width and height"></inpu> <div id="width"></div> <div id="height"></div> </head> <body> <script type="text/javascript"> let getWidthLength = function () { document.getElementById("width").innerHTML ="Width of the screen : " + screen.width; document.getElementById("height").innerHTML ="Height of the screen : " + screen.height; }; </script> </body> </html>
廣告