单击鼠标时折叠行

时间:2015-05-29 11:38:31

标签: javascript jquery html html5

我在互联网上找到了一个非常好的可折叠内容示例,但它尚未完成。

<div class="container faq_wrapper">
    <div class="row">
        <div class="span10 offset1">
            <p>
                &nbsp;</p>
            <div class="faq-all-actions">
                <a class="faq-expand" onclick="jQuery('.answer-wrapper').css('display','block');">Expand All</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class="faq-collapse" onclick="jQuery('.answer-wrapper').css('display','none');">Collapse All</a></div>
        </div>
    </div>
    <div class="row">
        <div class="span10 offset1">
            <div class="question-wrapper">
                <div class="arrow">
                    &nbsp;</div>
                <div class="big-q">
                    Q</div>
                <div class="question">
                    <h6>Can I try the software before I buy it?</div></h6>
                <div class="answer-wrapper">
                    <div class="big-a">
                        A</div>
                    <div class="answer">
                        Yes! Simply <a href="/trial">download a free trial</a> and you&#39;ll have instant access to all features for 30 days, absolutely free. We don&#39;t require your credit card details or any commitment.</div>
                </div>
            </div>    
        </div>
    </div>
</div>

单击行时,如何展开或隐藏示例中的答案?

3 个答案:

答案 0 :(得分:3)

即使没有使用CSS的JS,你也可以做到这一点。请看这个例子:

&#13;
&#13;
.collapsible > .item {
  display: block;
  cursor: pointer;
  margin: 5px;
}
.collapsible > .item > .row {
  display: block;
  background: #bbb;
  padding: 5px;
}
.collapsible > .item > .content {
  display: none;
  background: #ddd;
  padding: 5px;
}
.collapsible > .item > input[type=checkbox] {
  display: none;
}
.collapsible > .item > input[type=checkbox]:checked + .content {
  display: block;
}
&#13;
<div class="collapsible">
  <label class="item">
    <span class="row">Row 1</span>
    <input type="checkbox" />
    <span class="content">Content 1</span>
  </label>
  <label class="item">
    <span class="row">Row 2</span>
    <input type="checkbox" />
    <span class="content">Content 2</span>
  </label>
  <label class="item">
    <span class="row">Row 3</span>
    <input type="checkbox" />
    <span class="content">Content 3</span>
  </label>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将点击事件绑定到该行,并使用.find()

隐藏/显示该子项
<style>
    .answer-wrapper {
        display: none;
    }
</style>

$(document)
    .on('click','.row',function(){ 
        $(this).find('.answer-wrapper').slideToggle();
    })
;

http://jsfiddle.net/7bz5au97/

如果将事件绑定到文档,则不必担心由于ajax调用或动态内容而导致DOM更改。

答案 2 :(得分:0)

使用此功能,切换并查找

$('.row').click(function(){
  $(this).find('.answer-wrapper').toggle();
})
如果要动态添加行,请不要忘记使用

$('.row').on('click',function(){
  $(this).find('.answer-wrapper').toggle();
})