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

后端 未结 24 2789
名媛妹妹
名媛妹妹 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 10:59

    you can do this much easier with css only, for example : sass mode

    .truncatedText {
       font-size: 0.875em;
       line-height: 1.2em;
       height: 2.4em; // 2 lines * line-height
       &:after {
          content: " ...";
       }
    }
    

    and you have ellipsis ;)

    0 讨论(0)
  • 2020-11-22 11:00

    I rewrote Alex's function to use to the MooTools library. I changed it a bit to word jump rather than add the ellipsis in the middle of a word.

    Element.implement({
    ellipsis: function() {
        if(this.getStyle("overflow") == "hidden") {
            var text = this.get('html');
            var multiline = this.hasClass('multiline');
            var t = this.clone()
                .setStyle('display', 'none')
                .setStyle('position', 'absolute')
                .setStyle('overflow', 'visible')
                .setStyle('width', multiline ? this.getSize().x : 'auto')
                .setStyle('height', multiline ? 'auto' : this.getSize().y)
                .inject(this, 'after');
    
            function height() { return t.measure(t.getSize).y > this.getSize().y; };
            function width() { return t.measure(t.getSize().x > this.getSize().x; };
    
            var func = multiline ? height.bind(this) : width.bind(this);
    
            while (text.length > 0 && func()) {
                text = text.substr(0, text.lastIndexOf(' '));
                t.set('html', text + "...");
            }
    
            this.set('html', t.get('html'));
            t.dispose();
        }
    }
    });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 11:06

    DO THE ELLIPSIS USING ONLY CSS

    <html>
    <head>
    <style type="text/css">
    #ellipsisdiv {
        width:200px;
        white-space: nowrap;  
        overflow: hidden;  
        text-overflow: ellipsis;  
    }  
    </style>
    </head>
    <body>
    <div id="ellipsisdiv">
    This content is more than 200px and see how the the ellipsis comes at the end when the content width exceeds the div width.
    </div>
    </body>
    </html>
    

    *This code works on most current browsers. If you experience any problem with Opera and IE (which probably you won't), add these in the style:

    -o-text-overflow: ellipsis;  
    -ms-text-overflow: ellipsis;
    

    * This feature is part of CSS3. Its complete syntax is:

    text-overflow: clip|ellipsis|string;
    
    0 讨论(0)
  • 2020-11-22 11:07

    There's a solution for multi-line text with pure css. It's called line-clamp, but it only works in webkit browsers. There is however a way to mimic this in all modern browsers (everything more recent than IE8.) Also, it will only work on solid backgrounds because you need a background-image to hide the last words of the last line. Here's how it goes:

    Given this html:

    <p class="example" id="example-1">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    

    Here's the CSS:

    p {
        position:relative;
        line-height:1.4em;
        height:4.2em;      /* 3 times the line-height to show 3 lines */
    }
    p::after {
        content:"...";
        font-weight:bold;
        position:absolute;
        bottom:0;
        right:0;
        padding:0 20px 1px 45px;
        background:url(ellipsis_bg.png) repeat-y;
    }
    

    ellipsis_bg.png being an image of the same color of your background, that would be about 100px wide and have the same height as your line-height.

    It's not very pretty, as your text may be cut of in the middle of a letter, but it may be useful in some cases.

    Reference: http://www.css-101.org/articles/line-clamp/line-clamp_for_non_webkit-based_browsers.php

    0 讨论(0)
  • 2020-11-22 11:08

    The following CSS only solution for truncating text on a single line works with all browers listed at http://www.caniuse.com as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.

    .ellipsis {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
    }
    

    If you need support for earlier versions of Firefox check out my answer on this other question.

    0 讨论(0)
提交回复
热议问题