gpt4 book ai didi

javascript - 防止在菜单/导航系统的特定屏幕宽度下触发 jQuery 函数

转载 作者:行者123 更新时间:2023-11-28 12:19:18 25 4
gpt4 key购买 nike

我是使用 jQuery 的新手,并尝试编写一个基本的菜单系统,在屏幕宽度大于 480px 时,通过将鼠标悬停在 li 标签上展开子菜单,在宽度小于 480px 时,通过单击 li标记以展开子菜单。

我试图包括使用 Modernizr 检测媒体查询的能力,但是正如您将从我的尝试中看到的那样,它惨遭失败:

Working example. .....将鼠标悬停在名为“Properties”的 li 标签上

问题显然与代码没有获取屏幕大小调整有关,因为如果您以正确的宽度刷新浏览器,它可以在 > 480px 和 < 480px 下工作,但是当您调整浏览器大小时,这些函数仍然会尝试触发! !

我的代码:

// Main nav dropdown animation

$(document).ready(function() {
function doneResizing() {
if(Modernizr.mq('screen and (min-width: 481px)')) {

$("#sub-menu").hide();

$("#show-investment-type-nav").hover(function() {
$(this).find("#sub-menu").stop(true, true).slideDown("fast");
}, function() {
$(this).find("#sub-menu").stop(true, true).fadeOut("fast");
});

}
else if(Modernizr.mq('screen and (max-width: 480px)')) {

$("#sub-menu").hide();

var next_move = "show";

$("#show-investment-type-nav").click(function() {

$('#sub-menu').slideToggle(100);

if (next_move === "show") {
$("body").addClass("nav-active");
$("#site-nav #icon").empty().html("&#59236;");
$("#site-nav #nav-margin-down").animate({"margin-top": "163"}, 100);
next_move = "hide";
} else {
$("body").removeClass("nav-active");
$("#site-nav #icon").empty().html("&#59238;");
$("#site-nav #nav-margin-down").animate({"margin-top": "0"}, 100);
next_move = "show";
}
});
}
}

var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});

doneResizing();
});

任何关于为什么会发生这种情况的帮助都会很棒,它会帮助我学习!!

大家好!

最佳答案

试一试,看看它是否有效。我将点击处理程序移出了调整大小处理程序。在事件中绑定(bind)事件是棘手的,通常没有必要。我还必须移动 next_move 以将其放在全局范围内。使用 data() 将值添加到菜单元素可能是更好的选择:

var next_move = "show";

$(document).ready(function () {

$("#show-investment-type-nav").click(function () {
if (Modernizr.mq('screen and (max-width: 480px)')) {
$('#sub-menu').slideToggle(100);
if (next_move === "show") {
$("body").addClass("nav-active");
$("#site-nav #icon").empty().html("&#59236;");
$("#site-nav #nav-margin-down").animate({
"margin-top": "163"
}, 100);
next_move = "hide";
} else {
$("body").removeClass("nav-active");
$("#site-nav #icon").empty().html("&#59238;");
$("#site-nav #nav-margin-down").animate({
"margin-top": "0"
}, 100);
next_move = "show";
}
}
});

function doneResizing() {
if (Modernizr.mq('screen and (min-width: 481px)')) {
$("#sub-menu").hide();
$("#show-investment-type-nav").hover(function () {
$(this).find("#sub-menu").stop(true, true).slideDown("fast");
}, function () {
$(this).find("#sub-menu").stop(true, true).fadeOut("fast");
});
} else if (Modernizr.mq('screen and (max-width: 480px)')) {
$("#sub-menu").hide();
next_move = "show";
}
}

var id;
$(window).resize(function () {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});

doneResizing();
});

关于javascript - 防止在菜单/导航系统的特定屏幕宽度下触发 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962023/

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