Как получить ширину экрана устройства в JavaScript?
Опубликовано: 12 Декабря, 2021
Учитывая HTML-документ, запущенный на устройстве. Задача - найти ширину рабочего экрана устройства с помощью JavaScript.
Пример 1. В этом примере используется window.innerWidth для получения ширины экрана устройства. Свойство innerWidth используется для возврата ширины устройства.
<!DOCTYPE HTML>< html > < head > < title > How to get the device screen width in JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > <!-- Script to display the device screen width --> < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " width of the device's screen"; function GFG_Fun() { var width = window.innerWidth; el_down.innerHTML = width + " pixels"; } </ script > </ body ></ html > |
Выход:
- Перед нажатием на кнопку:

- После нажатия на кнопку:

Пример 2: В этом примере используется метод document.documentElement.clientWidth для получения ширины экрана устройства.
<!DOCTYPE HTML>< html > < head > < title > How to get the device screen width in JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > <!-- Script to display the device screen width --> < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " width of the device's screen"; function GFG_Fun() { el_down.innerHTML = document.documentElement.clientWidth + " pixels"; } </ script > </ body ></ html > |
Выход:
- Перед нажатием на кнопку:

- После нажатия на кнопку:
