Twitter Bootstrap使用“折叠”插件扩展文本

时间:2013-02-18 15:53:46

标签: javascript jquery twitter-bootstrap

有没有人想出如何使用显示某些文字的twitter bootstrap collapse plugin(例如,100个字符),然后点击按钮展开文字以显示其余内容?

Here's a JSFiddle that demonstrates the following issues I'm having

  1. 隐藏文字显示在行中。如果句子不会在视觉上受到干扰,那将更为可取。
  2. icon-plus-sign指示符的显示未切换(显示隐藏文字时不会消失,反之亦然)。
  3. 完全正常的HTML:

    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/js/bootstrap.min.js"></script>
    
    <div class="" data-toggle="collapse" data-target="#div1" >
         <span><b>Div1:</b> This is a sentence at the end of the first 100 characters that gets truncated </span>
     <i class='icon-plus-sign'></i> 
    </div>
    <div id="div1" class="collapse" >such that characters 101 to infinity are not shown inline with the beginning of the sentence (<b>Div1</b>).</div>
    
    <div class="" data-toggle="collapse" data-target="#div2" >
     <span><b>Div2:</b>This is a sentence at the end of the first 100 characters that gets truncated </span>
     <i class='icon-plus-sign'></i> 
    </div>
    <div id="div2" class="collapse" >such that characters 101 to infinity are not shown inline with the beginning of the sentence (<b>Div2</b>).</div>
    

2 个答案:

答案 0 :(得分:7)

我通过添加以下JavaScript来实现此目的:

$("div").on("hide", function() {
    $(this).prev("div").find("i").attr("class","icon-plus-sign");
    $(this).css("display","");
    $(this).css("height","5px");
});
$("div").on("show", function() {
    $(this).prev("div").find("i").attr("class","icon-minus-sign");
    $(this).css("display","inline");
    $(this).css("height","5px");
});

以下CSS:

div[data-toggle="collapse"] {
    float: left;
}

Example fiddle is here

旁注

我个人不会为此使用Bootstrap崩溃插件。我会使用像JQuery Expander这样的专用插件和Bootstrap图标。

另一个example fiddle is here

答案 1 :(得分:6)

我同意另一篇文章说崩溃插件不适用于此。实际上很容易写出能很好地处理这个问题的东西。例如,通过将隐藏文本包装在<span class="truncated">

<p>
 This is the visible part <span class="truncated">this is the hidden part.</span>
</p>

然后隐藏它,附加隐藏/显示图标,并切换状态:

$('.truncated').hide()                       // Hide the text initially
    .after('<i class="icon-plus-sign"></i>') // Create toggle button
    .next().on('click', function(){          // Attach behavior
    $(this).toggleClass('icon-minus-sign')   // Swap the icon
        .prev().toggle();                    // Hide/show the text
});

这利用了icon-minus-sign类优先于icon-plus-sign类的优先级,但如果它让您感觉更安全,则可以添加两者的切换。

演示:http://jsfiddle.net/VNdmZ/4/