【问题标题】:How to create a JQuery nav bar?如何创建一个 JQuery 导航栏?
【发布时间】:2012-05-29 05:28:58
【问题描述】:
我有一个侧面有 6 个导航按钮的网站。对于它们中的每一个,我想显示相应的 DIV 隐藏其他 5。页面加载时 DIV #1 可见,其他显示:无。
我知道如何使用 hide()、show()、fade 等隐藏和显示元素,但我正在尝试想出一种最佳方式来无缝显示被点击的元素,同时隐藏当前可见的元素,无需将它们全部拼写为:
$('#btn1').click(function(){
$('#div2').hide();
$('#div3').hide();
$('#div1').show();
)}
【问题讨论】:
标签:
jquery
hide
show
show-hide
【解决方案1】:
这就是我最终要做的事情。如果导航按钮被命名为“dc”之类的东西,那么隐藏和显示的 div 被命名为“dcdiv”
var which_id;
$(document).ready(function() {
$("#rightcontent>div:not(.default)").hide(); // hide all client divs but default one
$("#clientnav li").click(onClick); // event handler for nav bar
function doTransition(){
var which_name = which_id.split("#")[1];
$('#clientnav li[id="'+which_name+'"]').addClass("active");
$("#rightcontent>div:visible").slideUp("fast", function(){
var which_div = which_id+'div';
$(which_div).slideDown("fast");
});
}
function onClick(event){
$('#clientnav li').removeClass("active"); // remove active class for all nav buttons
which_id = "#" + $(this).attr("id"); // get the id of the nav button clicked on
doTransition();
event.preventDefault();
};
【解决方案2】:
这里是jquery代码:
$(document).ready(function() {
$('#btn-next').click(function () {
$('#recent_post').hide();
$('#top_post').fadeIn(3000).show();
return false;
});
$('#btn-prev').click(function () {
$('#top_post').hide();
$('#recent_post').fadeIn(3000).show();
return false;
});
});
这里是html:
<div id="top_post" class="post" style="z-index:1;">
<!---Content goes here--->
</div>
<div class="post" id="recent_post" style="display:none;z-index:0;">
<!---Content goes here--->
</div>
我已经在我的网站中实现了它。访问http://kaidul.web44.net/ 中的“文章”部分
我刚刚为两个 div 构建了它。为 6 个 div 做同样的工作。希望它有效!
【解决方案3】:
$('.commonBtn').click(function(){ // commonBtn is common class to all buttons
var index = this.id.replace('btn','');
$('div[id^=div]:visible').hide();
$('#div'+ index).show();
)};
【解决方案4】:
使用按钮的 ID,例如 btn_1 而不是 btn1
$('div[id^="btn"]').click(function(){
var id = $(this).attr("id").split("_")[1]; // fetch the id's number part
$('div[id^="div"]').hide(); // hide all divs with id starting with div
$("#div"+id).show(); // show corresponding div
)}