简体   繁体   中英

Truncate a string with the remaining space

I have a list where each li element contains two div inside one div "main" :

  • div "main" has a fixed width (saying 200px),

  • div "part1" has a variable width (that of text and image that contains)

=> I wish text inside div "part2" had as width that of div "main" less div "part1" (the remaining space)

EX:

...
<li>
   <div class="main">   
          <div class="part1">A</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
<li>
   <div class="main">   
          <div class="part1">ABC</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
<li>
   <div class="main">   
          <div class="part1">ABCDE</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
...

It should display:

A BlaBla...
ABC BlaB...
ABCDE Bl...

I tried but it doesn't work :

$(function(){
  $(".part1").each(function(){
    var $this = $(this);
    var $len = 0;
    var $len = $this.outerWidth();
    var $lenParent =$this.parent().outerWidth();        
    var newText2 = $this.next('.part2').text().substring(0,$lenParent-$len); 
    $this.next('.part2').innerHtml(newText2+"...");
  });
});

You don't need JavaScript for this, it can be done with styles. Change the css for part1 and part2 to display:inline

.part1,.part2
{
    display:inline;
}

Using the display: inline of Thinking Sites 's answer and the ellipse styles as suggested by epascarello this complete solution will now work:

.main{
    width: 100px;
    border: 1px solid red;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

.part1, .part2{
    display: inline;
}

See DEMO

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