[英]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.