Insert ellipsis (…) into HTML tag if content too wide

后端 未结 24 3004
名媛妹妹
名媛妹妹 2020-11-22 10:07

I have a webpage with an elastic layout that changes its width if the browser window is resized.

In this layout there are headlines (h2) that will have

24条回答
  •  春和景丽
    2020-11-22 11:02

    My answer only supports single line text. Check out gfullam's comment below for the multi-line fork, it looks pretty promising.

    I rewrote the code from the first answer a few times, and I think this should be the fastest.

    It first finds an "Estimated" text length, and then adds or removes a character until the width is correct.

    The logic it uses is shown below:

    enter image description here

    After an "estimated" text length is found, characters are added or removed until the desired width is reached.

    I'm sure it needs some tweaking, but here's the code:

    (function ($) {
        $.fn.ellipsis = function () {
            return this.each(function () {
                var el = $(this);
    
                if (el.css("overflow") == "hidden") {
                    var text = el.html().trim();
                    var t = $(this.cloneNode(true))
                                            .hide()
                                            .css('position', 'absolute')
                                            .css('overflow', 'visible')
                                            .width('auto')
                                            .height(el.height())
                                            ;
                    el.after(t);
    
                    function width() { return t.width() > el.width(); };
    
                    if (width()) {
    
                        var myElipse = "....";
    
                        t.html(text);
    
                        var suggestedCharLength = (text.length * el.width() / t.width()) - myElipse.length;
    
                        t.html(text.substr(0, suggestedCharLength) + myElipse);
    
                        var x = 1;
                        if (width()) {
                            while (width()) {
                                t.html(text.substr(0, suggestedCharLength - x) + myElipse);
                                x++;
                            }
                        }
                        else {
                            while (!width()) {
                                t.html(text.substr(0, suggestedCharLength + x) + myElipse);
                                x++;
                            }
                            x--;
                            t.html(text.substr(0, suggestedCharLength + x) + myElipse);
                        }
    
                        el.html(t.html());
                        t.remove();
                    }
                }
            });
        };
    })(jQuery);
    

提交回复
热议问题