[英]screen.width and screen.availwidth difference in javascript
[英]JavaScript Not getting an updated value when using screen.width or screen.availWidth in a function which is called by setInterval
預期行為:
setInterval
每 2 秒調用getScreenWidth()
。getScreenWidth()
獲取(瀏覽器)屏幕的當前寬度。輸出:
"1536"
輸出始終是一個恆定值。 (在我的情況下是 1536)
我正在 CodePen 上嘗試此代碼,並且嘗試過:
HTML:
<div id="demo"></div>
劇本:
"use strict";
console.clear();
function getScreenWidth() {
return screen.availWidth;
// I've also tried screen.width
}
const demo = document.getElementById("demo");
let count = 0;
const intervalId = setInterval(function () {
demo.innerHTML = getScreenWidth();
console.clear();
console.log(demo.innerHTML);
console.log(count);
count++;
if (count > 30) {
clearInterval(intervalId);
}
}, 2000);
由於setInterval
每 2 秒間接調用getScreenWidth()
,因此screen.width
不應該每次都是一個新值嗎?
如果我假設它是一個新值,那么這是否意味着screen.width
不等於瀏覽器窗口的當前寬度?
注意:代碼中的count
變量只是為了阻止setInterval
在后台無限期運行。
我有相同的屏幕寬度:)
無論如何,您不需要setInterval
您可以在每次使用 window onresize
事件調整瀏覽器大小時更改它:
window.onresize = function() {
screen.width; // 1536 / 1530 etc.
};
您也無法獲得瀏覽器寬度(使用screen.width
)
但是您可以使用 jQuery 的.width()
函數輕松獲取它:
$(window).width();
這是一個工作示例(使用 jQuery):
"use strict"; console.clear(); function getScreenWidth() { return $(window).width(); } const demo = document.getElementById("demo"); window.onresize = function() { demo.textContent = getScreenWidth(); console.clear(); console.log(demo.textContent); };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="demo"></div>
編輯:您也不能使用 JavaScript 調整瀏覽器窗口的大小。 這將是一個巨大的安全問題,您應該慶幸這是不可能的。
來自 MDN :
Screen 接口代表一個屏幕,通常是當前窗口正在渲染的屏幕,它是使用 window.screen 獲得的。
因此,這里的屏幕對象代表設備輸出顯示,而不是瀏覽器窗口。
再次, 來自 MDN :
Screen.width 只讀屬性返回以像素為單位的屏幕寬度。
因此, screen.width
(或window.screen.width
)沒有給我們瀏覽器窗口寬度,而是屏幕(設備輸出屏幕)寬度,這顯然不會改變。
要獲取瀏覽器窗口的寬度,我們需要使用Element.clientWidth
。
再次來自 MDN :
對於內聯元素和沒有 CSS 的元素,Element.clientWidth 屬性為零; 否則,它是元素的內部寬度(以像素為單位)。 它包括填充但不包括邊框、邊距和垂直滾動條(如果存在)。
當在根元素(元素)上使用 clientWidth 時(或者,如果文檔處於怪癖模式),則返回視口的寬度(不包括任何滾動條)。
只需更改getScreenWidth()
:
function getScreenWidth() {
return document.body.clientWidth;
}
現在,當瀏覽器窗口的寬度發生變化時,控制台輸出也會發生變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.