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

后端 未结 24 2792
名媛妹妹
名媛妹妹 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:53

    Well, one simple solution, that doesn't quite add the "...", but does prevent the

    from breaking into two lines would be to add this bit of css:

    h2 {
        height:some_height_in_px; /* this is the height of the line */
        overflow:hidden; /* so that the second (or third, fourth, etc.)
                            line is not visible */
    }
    

    I gave it some more thought, and I came up with this solution, you have to wrap the textual contents of your h2 tag with another tag (e.g. a span) (or alternatively wrap the h2s with something that has the given height) and then you can use this sort of javascript to filter out the unneeded words:

    var elems = document.getElementById('conainter_of_h2s').
                         getElementsByTagName('h2');
    
        for ( var i = 0, l = elems.length; i < l; i++) {
            var span = elems.item(i).getElementsByTagName('span')[0];
            if ( span.offsetHeight > elems.item(i).offsetHeight ) {
                var text_arr = span.innerHTML.split(' ');
                for ( var j = text_arr.length - 1; j>0 ; j--) {
                    delete text_arr[j];
                    span.innerHTML = text_arr.join(' ') + '...';
                    if ( span.offsetHeight <= 
                                            elems.item(i).offsetHeight ){
                        break;
                    }
                }
            }
        }
    

提交回复
热议问题