简体   繁体   中英

CSS ellipsis on text when resizing browser

I have a <table> with width set to 100%. Inside the <td> is a div with a text string that I want to add an ellipsis to if the width of text overflows.

In the javascript I set the width of the <div> to the width of the <td> and this works fine on load (or refresh) but I cannot get it to work onresize .

(don't worry about what I am actually doing here. It's part of a bigger table I've simplified for the sake of this question.)

Can anyone advise how I can get the text to ellipsis-ify onresize ?

 function doThis() { $('.divClass').css('width', $(".tdClass").css('width')); } 
 .divClass { width:0px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body onload="doThis()" onresize="doThis()"> <table style="width:100%"> <tr> <td class="tdClass"> <div class="divClass"> the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog </div> </td> </tr> </table> </body> 

Try to bind resize with browser's window if not working on body attribute

$(window).resize(function(){
   doThis()
});

I guess it can be done using only css. can you please try this code

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<style>
   /* Added new style property */
table,tr,td,tbody{
    width:100%;
    display:inline-block;

}
td{
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
}
  /* New style property end her */
</style>

</head>
<body>  <!-- //removed onload & onresize -->

<table>
    <tr>
        <td>  <!-- // removed the div -->
             the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog 

        </td>
    </tr>
</table>

</body>
</html>

Div is block element, so if you don't give any width, it will automatically take width of td. Means no script is required.

Try to make table responsive with display:block property so that div can get proper width from td element on resize.

table, thead, tbody, th, td, tr {
    display: block;
    height: auto;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM