javascript - 当内容分布在多行时显示更多内容的按钮

标签 javascript jquery html css

<div class="questionnaire-description col-xs-12" id="questionnaire_description_wrapper"> <text-truncate> <span ng-class="questionnaire_description.show_more ? 'full-description' : 'ph-ellipsis'" id="questionnaire_description"> <span class="ph-caption" ng-bind="questionnaire_details.description"></span> </span> </text-truncate> <span class="text-center questionnaire-sub-details" ng-if="!questionnaire_description.show_more"> <span class="ph-caption cursor-pointer" ng-bind="'SEARCH_SHOW_MORE'|translate" ng-click="questionnaire_description.show_more=true" ng-if="!questionnaire_description.show_more"></span> </span> </div> 我只想在文本很长以适合多行时才显示带省略号的更多按钮。如果只有一行,我什么都不要。 如果文本很长,我想要省略号并在第一行末尾显示更多内容。

enter image description here

最佳答案

您可以使用一些 JavaScript 和 text-overflow CSS 属性来完成这项工作。

使用 white-space: nowrap 使文本在一行中生成,而不会在多行中出现。

修复了 200px 和 overflow: hidden “剪切”文本,以便不是所有文本都可见。

然后,当应用 text-overflow: ellipsis 时,在文本溢出之前在文本末尾放置三个点。

“显示更多”/“显示更少”按钮只是在文本的两种状态之间切换。

var $text = jQuery(".text");
var $button = jQuery(".show-more");

$button.on("click", function(){
    $text.toggleClass("is-expanded");

    if($text.hasClass("is-expanded")){
        $button.text("Show less");
    } else {
        $button.text("Show more");
    }
});
.text {
    width: 200px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
.text.is-expanded {
    white-space: initial;
    overflow: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
This is very very long text and it is hidden at the end.
This is very very long text and it is hidden at the end. This is very very long text and it is hidden at the end.
This is very very long text and it is hidden at the end.
</div>
<button class="show-more">Show more</button>

关于javascript - 当内容分布在多行时显示更多内容的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632879/

相关文章:

javascript - 如何使用 Node.js 自动设置表单中的值

javascript - 将值格式化为千和百万

javascript - 使用键简化对象的设置值

javascript - 如何在此表单值之前添加或插入?

html - text-align right div + add padding-right 不改变 div 宽度?

javascript - 当拖动到其基础容器之外时,拖动消失

javascript - IE9 和 $(document).ready 失败,除非开发者控制台打开

javascript - jquery解开多个递归节点

Jquery Mobile 重置表单 html 5

javascript - 通过 jQuery/JS 验证 TEXTAREA 内的信息