问题描述
只是一个初学者,如果这是一个愚蠢的问题,那么抱歉。我试图让一个变量在浏览器窗口的宽度(以像素为单位)调整大小时不断更新。我不希望页面必须刷新才能更改变量,而是在调整窗口大小时更改变量。
我也不希望将该变量写入 html 文档中,因为我在该变量产生任何影响之前在数学上进一步使用该变量。
这是我认为最接近答案的。
提前致谢:)
window.onload = function() {
var windowwidth = window.innerWidth;
};
window.onresize = function() {
var windowwidth = window.innerWidth;
};
console.log(windowwidth);
在下面回答
window.onload = function() {
currentWidth(document.body.clientWidth);
};
window.onresize = function() {
currentWidth(document.body.clientWidth);
};
function currentWidth(w) {
// Math using w goes here
}
解决方法
最后使用以下 JS 代码并调整窗口大小。您可以在调整窗口大小时看到变量更改的值。
var a = Math.random();
console.log (a);
window.onresize = function()
{
a = Math.random();
console.log (a);
}
在回调中调用函数
window.onload = function() {
currentWidth(window.innerWidth);
};
window.onresize = function() {
currentWidth(window.innerWidth);
};
function currentWidth(w) {
console.log(w)
console.log(w > 500)
}