我有一小段 Javascript 检查加载时浏览器的宽度,并根据结果运行一段 jQuery。这将在移动设备上显示不同的菜单
但是,用户可能会在桌面上使用非常小的浏览器开始运行 jQuery(以及移动菜单)。如果他随后将大小调整为全屏,则菜单不会更改,因为不会再次运行对浏览器宽度的检查。
问题:我如何调整 Javascript 以便在每次调整浏览器大小时进行检查?
我的代码:
if (window.innerWidth <= 992) {
jQuery(document).ready(function($) {
$(".main-menu").hide();
$(".mobile-nav-button").click(function() {
$(".main-menu").slideToggle(500);
});
});
}
else {
jQuery(document).ready(function($) {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
});
}
最佳答案
您可以像这样使用调整大小函数包装器:
function resize(){
// do all your stuff here
}
然后在页面加载时调用一次,并在每次调整大小事件时调用它:
$(document).ready(function(){
resize();
$(window).resize(resize);
});
除了包装器,您还可以使用匿名函数 ($(window).resize(function(){/*Do stuff here*/})
),但这样您就不能在页面加载时调用您的函数,您必须自己重复一遍。
您的具体情况
在您的特定情况下,您必须准备好文件。它应该是这样的:
function resize(){
// First we need to show all, then we will selectively hide based on page width
$(".main-menu, .mobile-nav-button, .mobile-cart-button").show();
if (window.innerWidth <= 992) {
$(".main-menu").hide();
// also, because you bind a click event here, you'll need to unbind it every time
// otherwise it will be executed multiple times after a couple of resizes
// (you could also do what @david does and move this into the document.ready below)
$(".mobile-nav-button").off("click").click(function() {
// slideToggle will toggle display of an element, but because its wrapped in click()
// it only gets executed onclick, not resize. Also, you don't want animation on resize.
$(".main-menu").slideToggle(500);
});
} else {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
}
}
$(document).ready(function(){
resize();
$(window).resize(resize);
});
一个片段
下面是代码的片段。我将宽度减小到 700 像素,这样我就可以在更小的屏幕差异下看到效果(因为代码段编辑器的外观),但一切正常。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="mobile-nav-button">Mobile Nav Button</div>
<div class="mobile-cart-button">Mobile CART Button</div>
<div class="main-menu">MAIN MENU</dov>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function resize(){
$(".mobile-nav-button, .mobile-cart-button, .main-menu").show();
if (window.innerWidth <= 700) {
$(".main-menu").hide();
$(".mobile-nav-button").off("click").click(function() {
$(".main-menu").slideToggle(500);
});
} else {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
}
}
$(document).ready(function(){
resize();
$(window).resize(resize);
});
</script>
</body>
</html>
关于javascript - 调整大小后检查浏览器宽度,无需重新加载(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26524096/