jQuery windows.resize change variable and reload function wi



我有这个:

jQuery(document).ready(function($) {
windows_width();
menu_mobile();
function windows_width() {
var windows_width = $(window).width();
console.log('windows width = ' + windows_width);
}
$(window).resize(function() {
setTimeout (function () {
windows_width();
console.log('Windows resize');
},1000);
});
function menu_mobile() {
if (windows_width < 980) {
// MyFunction
} else {
return false;
}
}
});

但是我的函数"menu_mobile"不会将新值重新加载到"windows_width"变量。

目前尚不清楚您在这里要实现的目标

只有在加载窗口时,才会首次调用menu_mobile()函数。调整窗口大小时不调用它。此外,您正在检查 if 条件中未初始化变量的值

if (windows_width < 980)

如果您希望menu_mobile()函数在 DOM Ready 上执行,请尝试以下操作

jQuery(document).ready(function($) {
windows_width();
menu_mobile();
function windows_width() {
var windows_width = $(window).width();
console.log('windows width = ' + windows_width);
return windows_width;
}
$(window).resize(function() {
setTimeout (function () {
windows_width();
menu_mobile();
console.log('Windows resize');
},1000);
});
function menu_mobile() {
if (windows_width() < 980) {
console.log("menu_mobile");
} else {
return false;
}
}

当我尝试这个时:

jQuery(document).ready(function($) {
windows_width();
menu_mobile();
function windows_width() {
var windows_width = $(window).width();
console.log('Windows width = ' + windows_width);
return windows_width;
}
$(window).resize(function() {
setTimeout (function () {
windows_width();
menu_mobile();
console.log('Windows resizing');
},1000);
});
function menu_mobile() {
if (windows_width() < 980) {
console.log("menu_mobile");
} else {
return false;
}
}
});

当我在没有调整窗口大小的情况下加载我的网站时,我有这个控制台:

JQMIGRATE: Migrate is installed, version 1.4.1
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:20 Windows resizing
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:20 Windows resizing
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:20 Windows resizing
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:20 Windows resizing
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:13 Windows width = 873
general.js?ver=1.0:25 menu_mobile
general.js?ver=1.0:20 Windows resizing

为什么我的调整大小函数在加载页面上运行多次或只调整一个大小?

最新更新