JavaScript 如何获取设备屏幕的宽度

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>

输出:

JavaScript 如何获取设备屏幕的宽度

示例 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>

输出:

JavaScript 如何获取设备屏幕的宽度

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程