如何在 JavaScript 中获取屏幕的宽度和高度?
javascriptobject oriented programmingfront end technology更新于 2024/7/29 18:52:17
在本文中,我们将讨论如何在 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>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

