Javascript 如何在div之间切换
我有两个div。我希望加载页面时div id 1可见,当我单击main div中的任何位置时,div id 2应可见。当用户再次单击main 2时,main 2应隐藏且1可见`Javascript 如何在div之间切换,javascript,jquery,Javascript,Jquery,我有两个div。我希望加载页面时div id 1可见,当我单击main div中的任何位置时,div id 2应可见。当用户再次单击main 2时,main 2应隐藏且1可见` <div id="main" style="border:1 px dashed red;" > <div id="1" style="width:300px;height:50px; ">div One visible</div> <div id="2" style="
<div id="main" style="border:1 px dashed red;" >
<div id="1" style="width:300px;height:50px; ">div One visible</div>
<div id="2" style="width:300px;height:50px; ">div two visible</div>
</div>
第一分区可见
第二组可见
我如何使用Jquery完成它?我不知道如何获得切换效果
谢谢你,别客气
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
});
编辑 OP评论:“我是否可以跟踪哪个div是可见的?” 当然有,;这取决于你想如何使用它。您可以手动维护一个标志:
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2'),
$visible;
$2.hide(); // hide div#2 when the page is loaded
$visible = $1;
$main.click(function ()
{
$1.toggle();
$2.toggle();
$visible = ($visible === $1 ? $2 : $1);
});
});
或者,您也可以编写一个函数来计算:
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
如前所述,此函数可以用更简洁/简洁的形式编写:
function whichIsVisible()
{
return $1.add($2).filter(':visible');
}
但是,它在语义上与第一个版本不同。第一个版本返回以下内容之一:
$1
$2
未定义
$1
$2
,一个由两个元素组成的jQuery对象$1.添加($2)
,一个空的jQuery对象$()
编辑:修复了样式表(边框),因此“1”和“px”没有空间。;-) 工作示例发布在 HTML:
+1对于降级,如果未启用js,则不会启用隐藏divinaccessable@MattBall:So+.5表示速度,+.5表示清洁度。不幸的是,我的秤使用floor(),因此我不能给你任何分数。。。[jk;p]@Matt,我是否可以跟踪哪个div是可见的。一般来说,缓存DOM引用很好,但对于一次性访问来说,它毫无用处。MattBall:
return$1.add$2.filter(“:visible”)代码>@jAndy:那肯定更简洁了。我会把它加进去的。查一下表
<div id="main" style="border:1 px dashed red;" >
<div id="1" style="width:300px;height:50px; ">div One visible</div>
<div id="2" style="width:300px;height:50px;display:none; ">div two visible</div>
</div>
$(function() {
$('#main').click(function() {
$('#1, #2').toggle();
});
});
$(function(){
// start out hiding the second
$('#2').hide();
// when they click the main div
$('#main').click(function(){
// make one hide and the other show.
$('#1,#2').toggle();
});
});
<div id="main" style="border:1 px dashed red;" >
<div id="1" style="width:300px;height:50px; ">div One visible</div>
<div id="2" style="display:none;width:300px;height:50px; ">div two visible</div>
</div>
<a href="#" id="button">click</a>
$(document).ready(function() {
$("#button").click(function(event) {
$("#1").toggle();
$("#2").toggle();
})
});