单击div时隐藏div并显示第二个div

时间:2015-07-01 07:04:18

标签: jquery html css

这是我的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 个答案:

答案 0 :(得分:2)

点击外部.col-md-6 div后,您可以使用div选择器找到当前可见的:visible。然后,您可以hide()show() next()。试试这个:

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

Example fiddle

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

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

或者最后,如果你想在到达终点后循环遍历所有的div:

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

答案 1 :(得分: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>