JS / jQuery(隐藏div,点击显示div)

时间:2011-03-28 02:17:21

标签: javascript jquery

我有两个按钮。

我想要展示两个div。

每个div都有不同的内容。

我希望两个div只占用页面上相同的空间。

我想在页面加载时显示div1,如果他们点击链接div2,则div1消失,div2出现在其位置。

这样做的最佳方法是什么?怎么样?

7 个答案:

答案 0 :(得分:11)

所有初始的CSS和onload东西放在一边,你正在使用jquery, 我想你正在寻找像

这样的东西
$("#button2").click(function(){
    $("#div1").hide();
    $("#div2").show();
})

答案 1 :(得分:1)

页面加载:

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

点击链接:

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

答案 2 :(得分:1)

请在此处查看示例代码...希望这有助于:)

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

注意: 嗨凯尔, 我修改了我的代码,在jessegavin上添加了几行代码

答案 3 :(得分:0)

click处理程序中,请致电$('#div1').hide()$('#div2').show()

答案 4 :(得分:0)

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

然后在HTML ...

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

你应该添加事件监听器,但我猜你做到了这样......

答案 5 :(得分:0)

我要做的方法是首先给每个人一个唯一的ID(div1和div2就足够了)。你想要隐藏的div应该在tag style =“display:none”里面然后在你要点击以显示隐藏部分的div的标记内,使用这种类型的代码:onClick =“document.getElementById('div1 ')。style.display ='block'; document.getElementById('div2')。style.display ='none';“只需将div1和div2反转为另一种反转效果。

这是假设div1被隐藏,div2在开始时可见。

答案 6 :(得分:0)

请参阅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();
    });
}) 
相关问题