gpt4 book ai didi

JQuery resize() 窗口放大或缩小

转载 作者:行者123 更新时间:2023-12-01 06:52:08 24 4
gpt4 key购买 nike

我有这段代码,当单击按钮时显示/隐藏菜单

$('#main-menu ul').slideToggle();

当浏览器窗口小于 767 px 时,菜单会隐藏,因此会出现此按钮,允许打开和关闭它,这很有效,但唯一的问题是当我再次将窗口大小调整得更大时,菜单消失了,如果滑动切换已将其设置为不显示。为了解决这个问题,我添加了代码以在浏览器调整大小后显示菜单。当浏览器窗口再次缩小到小于 767 像素时,这会导致新菜单显示,而不是隐藏默认菜单。当缩放小于 767px 时,我可以再次隐藏菜单,但这会导致菜单在隐藏时闪烁。

我想知道一种方法来检测 resize() 是否在这种情况下放大或缩小,当缩小时我可以隐藏()菜单,当放大时我可以显示()菜单。

$('.menu-button').click(function() {
$('#main-menu ul').slideToggle();
});



$(window).resize(function(){
var w = $(window).width();
if(w > 767 && $('#main-menu ul').is(':hidden')) {
$('#main-menu ul').show();
}
});




$(window).resize(function(){
var w = $(window).width();
if(w < 767) {
$('#main-menu ul').hide();
}
});

最佳答案

您需要存储之前的尺寸,并根据该尺寸决定调整大小是增大还是减小。

jQuery(function($) {
// Cache a reference to $(window), for performance, and get the initial dimensions of the window
var $window = $(window),
previousDimensions = {
width: $window.width(),
height: $window.height()
};

$window.resize(function(e) {
var newDimensions = {
width: $window.width(),
height: $window.height()
};

if (newDimensions.width > previousDimensions.width) {
// scaling up
} else {
// scaling down
}

// Store the new dimensions
previousDimensions = newDimensions;
});
});

要在调整浏览器窗口大小并且用户选择显示菜单时保持菜单可见,您只需存储一个标志,表明用户选择使其可见:

$('.menu-toggle-button').click(function(e) {
var $menu = $('#main-menu ul');

if (!$menu.data('keepVisible')) {
$menu
.data('keepVisible', true); // Store the user's choice (show the menu)
.slideDown(); // Show the menu
} else {
$menu
.data('keepVisible', false); // Store the user's choice (hide the menu)
.slideUp(); // Hide the menu
}
});

$(window).resize(function() {
var $menu = $('#main-menu ul');

if ($(window).width() < 767) {
// Window is smaller than 767 pixels wide
if (!$menu.data('keepVisible')) {
// Hide the menu if it hasn't been kept visible by the user
$menu.hide();
}
} else if ($menu.is(':hidden') || $menu.data('keepVisible')) {
Window is larger than 767 pixels wide and the menu is invisible OR has been shown manually by the user
$menu
.data('keepVisible', false) // Reset the user's choice
.show(); // Show the menu
}
);

(请注意,使用此技术,完全不需要确定窗口变大还是变小的代码块)

关于JQuery resize() 窗口放大或缩小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com