欧美经典成人在观看线视频_嫩草成人影院_国产在线精品一区二区中文_国产欧美日韩综合二区三区

當前位置:首頁 > 編程技術 > 正文

js中如何獲得設備的寬高

js中如何獲得設備的寬高

在JavaScript中,你可以使用`window.innerWidth`和`window.innerHeight`來獲取設備的寬度和高度。以下是如何使用這些屬性的基本...

在JavaScript中,你可以使用`window.innerWidth`和`window.innerHeight`來獲取設備的寬度和高度。以下是如何使用這些屬性的基本示例:

```javascript

// 獲取設備的寬度

var width = window.innerWidth;

// 獲取設備的高度

var height = window.innerHeight;

console.log("Width: " + width + "px");

console.log("Height: " + height + "px");

```

這段代碼會輸出當前設備的屏幕寬度和高度,單位是像素(px)。如果你想要以不同的單位獲取寬高,可以使用`window.innerWidth`和`window.innerHeight`的`toString()`方法,并結合單位前綴:

```javascript

// 獲取設備的寬度,單位為百分比

var widthPercent = window.innerWidth + "px";

// 獲取設備的高度,單位為百分比

var heightPercent = window.innerHeight + "px";

console.log("Width: " + widthPercent);

console.log("Height: " + heightPercent);

```

請注意,`window.innerWidth`和`window.innerHeight`返回的是視口(viewport)的寬度和高度,不包括滾動條。如果你需要包括滾動條的尺寸,可以使用`document.body.clientWidth`和`document.body.clientHeight`,或者`document.documentElement.clientWidth`和`document.documentElement.clientHeight`(對于IE 8及以下版本)。

```javascript

// 獲取包含滾動條的窗口寬度

var widthWithScroll = document.body.clientWidth document.documentElement.clientWidth;

// 獲取包含滾動條的窗口高度

var heightWithScroll = document.body.clientHeight document.documentElement.clientHeight;

console.log("Width with scroll: " + widthWithScroll + "px");

console.log("Height with scroll: " + heightWithScroll + "px");

```

上一篇:電壓降單位mv