通过点击标题显示和消失 div 内容

Appearing and dissapearing div content by clicking on title

我对 jQuery 知之甚少,但我想在 html 中执行类似的操作:具有嵌套结构

<div id="special">
   <div>Some content</div>
   <div>Some content</div>
   <div>Some content</div>
</div>

并给出一些关于special的说明,这样里面的内容不会立即出现,而是只有在点击标题后才会出现,如果再次点击标题就会再次消失。如果能有像 accordion 中那样的效果就好了,但关键是要获得相同的结果,而不是单击另一个框,而是单击同一个框。

我想它一定是在某个地方完成的,但我不知道合适的关键字。任何想法或对已完成示例的参考都将非常有帮助和受欢迎。

这里有一个简单的方法可以做到这一点。我在 special 中添加了一个额外的 head 元素,用于切换行元素

$(function() {
  $("#head").click(function() {
    $(this).nextAll('.row').toggleClass('visible');
  });
});
#special {
  border: 1px solid red;
  display: table;
}
#head {
  height: 10px;
  border: 1px solid blue;
  display: table-row;
  cursor: pointer;
}
.row {
  display: none;
}
.visible {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="special">
  <div id="head">Header</div>
  <div class="row">Some content</div>
  <div class="row">Some content</div>
  <div class="row">Some content</div>
</div>

不知道我说得对不对,但是我的建议是:

Javascript

$('h1').on('click', function(){
    $(this).next('div').slideToggle();
});

HTML

<h1>Special</h1>
<div id="special">
   <div>Some content</div>
   <div>Some content</div>
   <div>Some content</div>
</div>

CSS

#special{
    display: none;
}

Demo

也可以 在纯 CSS 中做到这一点。可能看起来像:

div#special {
  height: 20px;
  width: 100px;
  background-color: red;
}

div#special:before {
  position: absolute;
  content: 'click me!';
  color: white;
}

div#special:focus:before {
  display: none;
}

div#special:focus {
  background-color: transparent;
}

div#special > div {
  display: none;
}

div#special:focus > div {
   display: block;
}

但是您还需要稍微修改一下 HTML,我们需要 tabIndex 才能正常工作

<div id="special" tabIndex="1">
   <div>Some content</div>
   <div>Some content</div>
   <div>Some content</div>
</div>

演示http://jsbin.com/zatevunewo/1/edit?html,css,output

HTML

<button class="title">Title</button>
<div id="special">
   <div>Some content</div>
   <div>Some content</div>
   <div>Some content</div>
</div>

jQuery

$('.title').click(function() {
    $('#special').toggle('slow');
});

Demo

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<div id="special" style="width:200px;height:200px;background:green;">
   <div id="special1" style="width:200px;height:20px;background:red;">Some content</div>
   <div>Some content</div>
   <div>Some content</div>
</div>

<script>
    $("#special").click(function(){
        $("#special1").toggle();
});
</script>

单击 div 上的任意位置 #special... #special1 出现并在下次单击时消失..