Shrink DIV to text that's wrapped to its max-width?

前端 未结 3 1505
耶瑟儿~
耶瑟儿~ 2020-11-29 11:11

Shrink wrapping a div to some text is pretty straightforward. But if the text wraps to a second line (or more) due to a max-width (as an example) then the size of the DIV do

3条回答
  •  甜味超标
    2020-11-29 11:31

    It's not the prettiest solution but it should do the trick. The logic is to count the length of each word and use that to work out what the longest line is that will fit before being forced to wrap; then apply that width to the div. Fiddle here: http://jsfiddle.net/uS6cf/50/

    Sample html...

    testing testing
    testing testing
    testing
    testing
    testing 123 testing
    testing 123 testing

    And the javacript (relying on jQuery)

    $.fn.fixWidth = function () {
        $(this).each(function () {
            var el = $(this);
            // This function gets the length of some text
            // by adding a span to the container then getting it's length.
            var getLength = function (txt) {
                var span = new $("");
                if (txt == ' ')
                    span.html(' ');
                else
                    span.text(txt);
                el.append(span);
                var len = span.width();
                span.remove();
                return len;
            };
            var words = el.text().split(' ');
            var lengthOfSpace = getLength(' ');
            var lengthOfLine = 0;
            var maxElementWidth = el.width();
            var maxLineLengthSoFar = 0;
            for (var i = 0; i < words.length; i++) {
                // Duplicate spaces will create empty entries.
                if (words[i] == '')
                    continue;
                // Get the length of the current word
                var curWord = getLength(words[i]);
                // Determine if adding this word to the current line will make it break
                if ((lengthOfLine + (i == 0 ? 0 : lengthOfSpace) + curWord) > maxElementWidth) {
                    // If it will, see if the line we've built is the longest so far
                    if (lengthOfLine > maxLineLengthSoFar) {
                        maxLineLengthSoFar = lengthOfLine;
                        lengthOfLine = 0;
                    }
                }
                else // No break yet, keep building the line
                    lengthOfLine += (i == 0 ? 0 : lengthOfSpace) + curWord;
            }
            // If there are no line breaks maxLineLengthSoFar will be 0 still. 
            // In this case we don't actually need to set the width as the container 
            // will already be as small as possible.
            if (maxLineLengthSoFar != 0)
                el.css({ width: maxLineLengthSoFar + "px" });
        });
    };
    
    $(function () {
        $(".fixed").fixWidth();
    });
    

提交回复
热议问题