点击div时隐藏它并显示第二个div。

3
这是我的HTML代码...在其中,我将第二个div的"display:none"设置为了隐藏状态。当我点击灰色的第一个div时,希望第二个div出现并消失第三个和第一个div;当我点击第二个div时,希望第三个和第一个div消失...请给我一些帮助,我是网站设计的新手。
<div class="row">
    <div class="col-md-6">
        <div style="background:grey">
            text here
        </div>
        <div style="background:blue;display:none">
            text here
        </div>
        <div style="background:green;display:none">
            text here
        </div>
    </div>
</div>
2个回答

2

当单击外部的.col-md-6 div时,您可以使用:visible选择器查找当前可见的div。然后,您可以hide()它,并show()下一个div。请尝试以下操作:

$('.col-md-6').click(function() {
    $(this).find('div:visible').hide().next().show();
});

实例代码

或者,如果您不想允许某人隐藏最终的 div

$('.col-md-6').click(function() {
    var $current = $(this).find('div:visible');
    var $next = $current.next()
    if ($next.length) {
        $current.hide();
        $next.show();
    }
});

最后,如果您想循环遍历所有

,并在到达末尾时返回开头:

$('.col-md-6').click(function() {
    var index = $(this).data('index') || 1;
    var $divs = $(this).find('div');
    $divs.hide().eq(index % $divs.length).show();
    $(this).data('index', ++index);
});

谢谢@Rory...提供如此简单的解决方案...先生,有没有办法,如果我点击第一个div,它会以翻转(Y)的方式消失,第二个div也是一样的呢? - farkhund

0
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <script>
     $(document).ready(function(){
     $("#blue").hide();
     $("#green").hide();

$("#grey").on("click",function(){
    $("#blue").show(3000);
    $("#grey").hide(2000);
    $("#green").hide(2000);
});
$("#blue").on("click",function(){
   $("#green").show(3000);
    $("#blue").hide(2000);
    $("#grey").hide(2000);
});
$("#green").on("click",function(){
   $("#grey").show(3000);
    $("#blue").hide(2000);
    $("#green").hide(2000);
});

});
</script>



<div class="row">
<div class="col-md-6">
    <div style="background:grey;height:50px" id="grey">
        text here
    </div>
    <div style="background:blue;height:50px" id="blue">
        text here
    </div>
    <div style="background:green;height:50px" id="green">
        text here
    </div>
   </div>
</div>
</body>
</html>

有没有办法,如果我点击第一个div,它会以翻转(Y)的方式消失,然后同样的操作适用于第二个div吗? - farkhund
请查看以下链接以了解不同的过渡效果:http://api.jquery.com/hide/我已经使用一个过渡效果更改了上面的代码。 - Gisha Ajeesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接