如果条件总是在$(window).resize函数内部工作

我有这个脚本,我希望当窗口小于768px console.log('less than 768px'); 但我的脚本始终工作时窗口超过768px请帮助我某人:(

  var width = $(window).width(); $(window).on('resize',function(){ if (width < 768){ console.log('less than 768px'); }else{ console.log('nothing'); } }); 

您需要获取resize事件回调中的宽度以获取更新的值:

 $(window).on('resize',function(){ var width = $(window).width(); if (width < 768){ console.log('less than 768px'); }else{ console.log('nothing'); } }); 

您需要在resize处理程序中设置width变量,否则它只使用在页面加载时设置的窗口宽度。

 $(window).on('resize',function(){ var width = $(window).width(); if (width < 768){ console.log('less than 768px'); } else { console.log('nothing'); } }); 

这在设置宽度值时有效

 $(window).resize(function (){ var width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth; if (width < 768){ console.log('less than 768px'); } else{ console.log('nothing'); } })