开发者

JS/jQuery (Hide div, show div on click)

I have two buttons.

I have two divs I want to show.

Each divs have different content.

I want both divs to only take up the same amount of space on the page.

I want it so on page load, di开发者_如何学JAVAv1 is shown, and if they click link div2, div1 disappears and div2 appears in its place.

What is the best way to go about doing this? and how?


All the initial CSS and onload stuff aside and you're using jquery, I think you're looking for something like

$("#button2").click(function(){
    $("#div1").hide();
    $("#div2").show();
})


page load:

$('#div2').hide();

click link:

$('#div1').hide(); $('#div2').show();


see the sample code here... hope this helps :)

http://jsfiddle.net/jpHzk/2/

Note: Hi Kyle, I modified my code, added a few lines on it courtesy of jessegavin


In a click handler, call $('#div1').hide() and $('#div2').show().


function showdiv(id){
    $("#container div").hide(0); //Hide all DIV's within container
    $("#container #" + id).show(); //Show DIV with certain ID
}

Then in HTML...

<a href="javascript:;" onclick="javascript:showdiv('about');">About Us</a>
<a href="javascript:;" onclick="javascript:showdiv('contact');">Contact</a>

You should add event listeners, but I guess you did it something like this..


The way that I'd go about doing it is by giving each one a unique ID first (div1 and div2 would suffice). The div you want hidden should have inside the tag style="display:none" Then within the tag of the div that you want to click to show the hidden parts, use this type of code: onClick="document.getElementById('div1').style.display='block'; document.getElementById('div2').style.display='none';" Just reverse div1 and div2 on the other for the inverse effect.

This was assuming div1 was hidden and div2 was visible at the start.


See working version on jsFiddle: http://jsfiddle.net/7jWVt/

HTML

<button id="button1">One</button>
<button id="button2">Two</button>
<div id="div1">
    Here is line one<br/>
    Here is line two<br/>
    Here is line three<br/>
    Here is line four
</div>
<div id="div2">
    Here is line one<br/>
    Here is line two
</div>
<p> Here's some other paragraph to show that 
    the divs will take up the same amount of space</p>

jQuery

$(function() {

    // Make the divs have equal heights
    var h1 = $("#div1").height();
    var h2 = $("#div2").height();
    $("#div1,#div2").height(Math.max(h1,h2));

    // Then hide the second div
    $("#div2").hide();

    // Then add a click handlers to the buttons
    $("#button1").click(function() {
      $("#div1").show();
      $("#div2").hide();
    });
    $("#button2").click(function() {
      $("#div1").hide();
      $("#div2").show();
    });
}) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜