在显示另一个元素之后如何使元素消失?

时间:2017-05-17 18:46:49

标签: jquery

有一些按钮可以切换三个不同元素的类:第一个按钮显示 - 隐藏第一个元素,第二个按钮显示 - 隐藏第二个元素,依此类推。

问题在于,当下一个元素出现时,前一个元素不会消失。如何按下某个按钮后,页面上只有一个当前元素?

嗯,目标是:我按下第一个按钮 - 显示第一个元素,按第二个按钮,然后第一个元素消失,第二个元素显示。

$(function() {

    // show-hide content ONE
    $('.show-content-one').on('click', function(){
        $('#hidden-content-one').toggleClass('hidden-content-one-show');
    });
    $('.close-content-one').on('click', function(){
        $('#hidden-content-one').toggleClass('hidden-content-one-show');
    });

    // show-hide content TWO
    $('.show-content-two').on('click', function(){
        $('#hidden-content-two').toggleClass('hidden-content-two-show');
    });
    $('.close-content-two').on('click', function(){
        $('#hidden-content-two').toggleClass('hidden-content-two-show');
    });

    // show-hide content THREE
    $('.show-content-three').on('click', function(){
        $('#hidden-content-three').toggleClass('hidden-content-three-show');
    });
    $('.close-content-three').on('click', function(){
        $('#hidden-content-three').toggleClass('hidden-content-three-show');
    });

});

我研究了这个例子

http://blogs.html5andcss3.org/show-and-hide-multiple-div-using-javascript/

但在我的情况下不能使用它。我想应该有类似条件的东西:如果某个元素有(或没有)某个类 - 那么就这样做。

这是我的example

2 个答案:

答案 0 :(得分:1)

这是一个使用按钮索引的简单示例,该索引与您要显示的div的索引相匹配。

(function($){$(function(){
  // start all hidden
  var divs = $('.container > div')
  divs.hide()
  
  $('.buttons button').on('click', function(event){
    // hide all
    divs.hide();
    
    // show the div that matches the button index
    divs.eq($(this).index()).show()
  })
})})(jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="buttons">
<button>show 1</button>
<button>show 2</button>
<button>show 3</button>
</div>

<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>

答案 1 :(得分:1)

这可以非常经济地完成如下:

<强> CSS

替换:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout_that_contains_spinner);
    spinner = (Spinner) findViewById(R.id.spinner);

    .............
    ...................... 
}

使用:

#hidden-content-one,
#hidden-content-two,
#hidden-content-three {
    position: relative;
    height: 0;  
    overflow: hidden; 
}
.hidden-content-one-show,
.hidden-content-two-show,
.hidden-content-three-show {
    height: 100px !important; 
    padding: 10px;
}

<强>的Javascript

将现有的javascript替换为:

.wrapper > div {
    position: relative;
    height: 100px; 
    padding: 10px;
    overflow: hidden;
    display: none;
}

<强> Demo

这将容纳任意数量的按钮/内容。

相关问题