我有一个侧面有 6 个导航按钮的网站。对于它们中的每一个,我想显示相应的 DIV 隐藏其他 5。页面加载时 DIV #1 可见,其他显示:无。
我知道如何使用 hide()、show()、fade 等隐藏和显示元素,但我正在尝试想出最好的方法来无缝显示被点击的元素,同时隐藏当前可见的元素,而无需求助于拼写他们都像:
$('#btn1').click(function(){
$('#div2').hide();
$('#div3').hide();
$('#div1').show();
)}
$('.commonBtn').click(function(){ // commonBtn is common class to all buttons
var index = this.id.replace('btn','');
$('div[id^=div]:visible').hide();
$('#div'+ index).show();
)};
使用按钮的 idbtn_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
)}
这是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 做同样的工作。希望它有效!
这就是我最终要做的事情。如果导航按钮被命名为“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();
};