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

我有两个按钮。

我想要展示两个div。

每个div都有不同的内容。

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

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

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

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

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

在这里看到示例代码…希望这有帮助:)

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

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

页面加载:

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

点击链接:

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

click处理程序中,调用$('#div1').hide()$('#div2').show()

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

然后在HTML中……

 About Us Contact 

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

我要做的方法是首先给每个人一个唯一的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在开始时可见。

请参阅jsFiddle上的工作版: http : //jsfiddle.net/7jWVt/

HTML

   
Here is line one
Here is line two
Here is line three
Here is line four
Here is line one
Here is line two

Here's some other paragraph to show that the divs will take up the same amount of space

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(); }); })