JavaScript 如何获取设备屏幕的宽度
给定一个正在设备上运行的HTML文档,并且任务是使用JavaScript找到工作屏幕设备的宽度。
示例1: 这个示例使用 window.innerWidth 来获得设备屏幕的宽度。使用 innerWidth属性 来返回设备的宽度。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get the width of device
screen in JavaScript?
</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on Button to Get the
Width of Device's Screen
</h3>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG"></p>
<!-- Script to display the device screen width -->
<script>
let elm = document.getElementById("GFG");
function GFG_Fun() {
let width = window.innerWidth;
elm.innerHTML = width + " pixels";
}
</script>
</body>
</html>
输出:
示例 2: 此示例使用 document.documentElement.clientWidth方法 获取设备屏幕宽度。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get the width of device
screen in JavaScript?
</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on Button to Get the
Width of Device's Screen
</h3>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG">
</p>
<!-- Script to display the device screen width -->
<script>
let elm = document.getElementById("GFG");
function GFG_Fun() {
elm.innerHTML = document.
documentElement.clientWidth + " pixels";
}
</script>
</body>
</html>
输出: