我如何在div之间切换 [英] how do i toggle between divs

查看:112
本文介绍了我如何在div之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个div.我希望在加载页面时显示div ID 1,并且当我在主div ID 2中的任何位置单击时应该可见.当用户再次单击主ID 2时应该隐藏并且1可见.

I have 2 divs. I want div id 1 to be visible when the page is loaded and when i click on anywhere in main div id 2 should be visible.when user click again on main 2 should be hidden and 1 visible.`

<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完成它?我不确定如何获得切换效果

How do i get it done using Jquery? i am not sure how to get the toggling effect

谢谢

推荐答案

轻松自如.

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

jsfiddle演示→

OP评论:无论如何,我是否可以跟踪可见的div?"

当然有;这取决于您要如何使用它.您可以手动维护一个标志:

There certainly is; it depends on how you want to use it. You can manually maintain a flag:

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

或者您也可以编写一个为您解决的函数:

Or you can just write a function that figures it out for you:

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

jAndy 指出,此函数可以更简洁/简洁的形式编写:

As jAndy points out, this function can be written in a more concise/terse form:

function whichIsVisible()
{
    return $1.add($2).filter(':visible');
}

但是,它与第一个版本在语义上有所不同.第一个版本返回以下内容之一:

However, it is semantically different from the first version. The first version returns one of:

  • $1
  • $2
  • undefined
  • $1
  • $2
  • undefined

而jAndy的版本返回以下值之一:

while jAndy's version returns one of:

  • $1
  • $2
  • $1.add($2),一个包含两个元素的jQuery对象
  • $(),一个空的jQuery对象
  • $1
  • $2
  • $1.add($2), a two-element jQuery object
  • $(), an empty jQuery object

因此,它们不是严格等同的.

这篇关于我如何在div之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆