關於文字超過指定範圍的自動截取

今天下午客戶有要求這件事, 舉實際例子說明比較快:

《天然除垢幫手組》除舊佈新超值組,律動SONETT- 《天然除垢幫手組》除舊佈新超值組律動SONETT線上訂購系統

他希望改成:
《天然除垢幫手組》除舊佈新超值
組,律動SONETT- 《天然除垢...

希望限制在兩行, 多出來的部分截掉且加上 "..."

去survey 了一下, 發現css 只有支援單行的形式
 text-overflow: ellipsis;
http://ant4css.blogspot.com/2009/03/text-overflow.html
https://developer.mozilla.org/en/CSS/text-overflow

於是乎我利用關鍵字 "Ellipsis js" 去查google, 得到下列有用的文章, 把這個問題解掉了
http://stackoverflow.com/questions/536814/insert-ellipsis-into-html-tag-if-content-too-wide

js code 片段:

(function($) {
            $.fn.ellipsis = function(){
                return this.each(function()
                {
                        var el = $(this);

                        if(el.css("overflow") == "hidden")
                        {
                                var text = el.html();
                                var multiline = el.hasClass('multiline');
                                var t = $(this.cloneNode(true))
                                        .hide()
                                        .css('position', 'absolute')
                                        .css('overflow', 'visible')
                                        .width(multiline ? el.width() : 'auto')
                                            .height(multiline ? 'auto' : el.height())
                                            ;

                                    el.after(t);

                                    function height() { return t.height() > el.height(); };
                                    function width() { return t.width() > el.width(); };

                                    var func = multiline ? height : width;

                                    while (text.length > 0 && func())
                                    {
                                            text = text.substr(0, text.length - 1);
                                            t.html(text + "...");
                                    }

                                    el.html(t.html());
                                    t.remove();
                            }
                    });
            };
        })(jQuery);




html 片段

.ellipsis {
        white-space: nowrap;
        overflow: hidden;
}
.ellipsis.multiline {
        white-space: normal;
}
<div class="ellipsis" style="width: 100px; border: 1px solid black;">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<div class="ellipsis multiline" style="width: 100px; height: 40px; border: 1px solid black; margin-bottom: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<script type="text/javascript" src="/js/jquery.ellipsis.js"></script>
<script type="text/javascript">
$(".ellipsis").ellipsis();
</script>

同時也藉由這個簡單的jQuery plugin 學習到了 plugin 的寫法 :)


留言

熱門文章