我知道。标题有点……难懂。我会尽力帮助您理解它。
基本上,我为我的个人网站所做的就是将主导航作为网页的主体。单击链接时,它会加载一些隐藏的内容,如下所示:
$(document).ready(function(){
$('li a#about-toggle').click(function(){
$('li#about').animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
$('li a#portfolio-toggle').click(function(){
$('li#portfolio').animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
$('li a#resume-toggle').click(function(){
$('li#resume').animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
$('li a#contact-toggle').click(function(){
$('li#contactme').animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
});
目前,这允许网站的访问者打开所有元素,这不仅在视觉上令人不快,而且会产生一些错误,但主要是在视觉上令人不快。
我的问题是,在我尽可能保持代码完好无损的情况下,我该如何做到让它们一次只能打开一个?
提前致谢, 雅各布
编辑:
$(document).ready(function(){
$('#about-toggle').click(function(){
$("li.active").addClass("hidden");
$('#about').animate({"height": "toggle", "opacity": "toggle"}, "slow").removeClass("hidden").addClass("active");
});
$('#portfolio-toggle').click(function(){
$("li.active").addClass("hidden");
$('#portfolio').animate({"height": "toggle", "opacity": "toggle"}, "slow").removeClass("hidden").addClass("active");
});
$('#resume-toggle').click(function(){
$("li.active").addClass("hidden");
$('#resume').animate({"height": "toggle", "opacity": "toggle"}, "slow").removeClass("hidden").addClass("active");
});
$('#contact-toggle').click(function(){
$("li.active").addClass("hidden");
$('li#contactme').animate({"height": "toggle", "opacity": "toggle"}, "slow").removeClass("hidden").addClass("active");
});
});
最佳答案
在所有要关闭的元素上放置一个公共(public)类。关闭除您单击的那个以外的所有其他选项,然后打开您单击的那个。当您再次关闭它们时,已经关闭的将不会执行任何操作。
假设您为每个元素都添加了 togglers
类,那么您可以这样做并将所有元素的 jQuery 缩短为一个 block :
$(document).ready(function(){
$('#about-toggle, #portfolio-toggle, #resume-toggle, #contact-toggle').click(function(){
// get the clicked on id and convert it to shortened form
var id = this.id.replace(/\-.*$/, "");
var item = $("#" + id);
// toggle others that are open and toggle the current one
$(".togglers").not(".hidden").add(item).animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
});
或者,如果你不把公共(public)类放在它们上面,那么你只需要列出它们:
$(document).ready(function(){
$('#about-toggle, #portfolio-toggle, #resume-toggle, #contact-toggle').click(function(){
// get the clicked on id and convert it to shortened form
var id = this.id.replace(/\-.*$/, "");
var item = $("#" + id);
// toggle others that are open and toggle the current one
$('#about, #portfolio, #resume, #contact').not(".hidden").add(item).animate({"height": "toggle", "opacity": "toggle"}, "slow").toggleClass("hidden");
});
});
此实现假定 .hidden
类应用于切换为关闭状态的任何项目以及从任何打开的项目中删除的项目,并且初始 HTML 状态必须与之匹配。
关于javascript - 在 jQuery 中打开一个元素时如何关闭其他打开的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11840983/