CSS Overflow Detection in JavaScript

overflowThere are a number of ways to display a line of text (for example, on a forum) and end this line with "..." if the text overflows the line (without trimming using the CSS property ). I'm still looking for a better solution. For instance,

Adding "..." to the CSS as a background image is a possibility, but it will appear all the time, and this is not a good solution.

Some sites simply count characters, and if more than 100, truncates the string to save only 100 (or 97) characters and add "..." at the end. But fonts are usually not proportional, so the result is not very good. For example, space - in pixels - accepted

  • "AAA" and "iii" are clearly different
  • "AAA"and "iii"through the proportional font have the same width

There is another idea to get the exact size in pixels of a row:

  • create in javascript a div
  • insert text into it (for example, via innerHTML)
  • measure width (via .offsetWidth)

which is not yet implemented. However, I wonder if there could be a browser compatibility issue?
Has anyone tried this solution? Other recommendations would be welcome.

+3
source share
3 answers

So, with a little JS, I was able to get it working: http://jsfiddle.net/ug8Fc/3/

, , , "" ( , ). , , , . , .

- , , jquery, .

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">  
  <style type='text/css'>
    table {
      border: 1px solid #000;
      border-collapse: collapse;
      border-spacing: 0;
      width: 800px;
    }
    table thead {
      background-color: #AAA;
      color: #333;
    }
    table tbody tr {
      border: 1px solid #000;
    }
    table tbody td {
      padding: 2px;
    }
    .from {
      width: 100px;
    }
    .preview {
    }
    .date {
      width: 90px;
    }
  </style>
  <script type='text/javascript'>
  //<![CDATA[ 
  $(window).load(function(){
    // Create a span we can use just to test the widths of strings
    var spanTest = $('<span>').css('display','none').attr('id','span-test-tester');
    $('body').append(spanTest);

    // function to get the length of a string
    function getLength(txt){
        return spanTest.text(txt).width();
    }

    // now make all the previews fit
    $('table tbody .preview').each(function(){
        // build a bench-mark to gauge it from
        var roomWidth = $(this).innerWidth();

        // now, get the width and play with it until it fits (if it doesn't)
        var txt = $(this).text();
        var contentsWidth = getLength(txt);
        if (contentsWidth > roomWidth){ // bigger than we have to work with
            roomWidth -= getLength('...'); // work within confines of room + the ellipsis
            while (contentsWidth > roomWidth){ 
                txt = txt.substring(0,txt.length-1);
                contentsWidth = getLength(txt);
            }
            // set the text to this
            $(this).text(spanTest.text()).append($('<span>').text('...'));
        }
    });

  });
  //]]> 
  </script>
</head>
<body>
  <table>
    <thead>
      <tr>
        <th class="from">From</th>
        <th class="preview">Subject</th>
        <th class="date">Date</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="from">Joe Smith</td>
        <td class="preview">Hello bob, I just wanted to check in and see how things were going.
            I know we spoke last week about etc. etc. etc.</td>
        <td class="date">Dec 1, 2010</td>
      </tr>
      <tr>
        <td class="from">John Doe</td>
        <td class="preview">Hey bob, got any plans for new years yet?</td>
        <td class="date">Dec 28, 2010</td>
      </tr>
      <tr>
        <td class="from">Ben Franklin</td>
        <td class="preview">Happy New Year! Hope you had a great time at the casinos (and didn't
            spend too much money (haha)). Hope to see you this Memorial day blah blah blah
      </tr>
    </tbody>
  </table>
</body>
</html>
+3

css text-overflow: ellipsis. javascript.

http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

+3

, !

:

1/

:

<td class="preview">Hey bob, got any plans for new years yet?</td>

:

<td><div class="preview">Hey bob, got any plans for new years yet?</div></td>

2/ script doens't (, , ...)

"" , . ( ):

    (...)
    // build a bench-mark to gauge it from
    var roomWidth = $(this).innerWidth();

    // now, get the width and play with it until it fits (if it doesn't)
    var fontSize=$(this).css("font-size");
    spanTest.css("font-size", fontSize);
    var fontStyle=$(this).css("font-style");
    spanTest.css("font-style", fontStyle);
    var fontWeight=$(this).css("font-weight");
    spanTest.css("font-weight", fontWeight);
    var fontFamily=$(this).css("font-family");
    spanTest.css("font-family", fontFamily);
    (...)

3/

1000 , 25 ( Firefox 7) script 40 .

, "display: none".

"position: absolute; top: -100px" : 11 1000 !

, :

var spanTest = $('<span>').css('display','none').attr('id','span-test-tester');

:

var spanTest = $('<span>').attr('id','span-test-tester').css('position','absolute').css('top','-100px');

:

script... !

, -...:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">  
  <style type='text/css'>

    .preview {    
    }

    .backg{
      background:red;
      margin: 20px 0;
      border:1px solid blue;
      width:200px;
      padding:10px;
      font-size:14px;  // change it to test with other fonts
      font-weight:bold;
    }

  </style>
  <script type='text/javascript'>
  //<![CDATA[ 
  $(window).load(function(){
   truncate();
  });


  function truncate(){

    // Create a span we can use just to test the widths of strings
    var spanTest = $('<span>').attr('id','span-test-tester').css('position','absolute').css('top','-100px');
    $('body').append(spanTest);

    // function to get the length of a string
    function getLength(txt){
        return spanTest.text(txt).width();
    }

    var nb =0;
    // now make all the previews fit
    $('.preview').each(function(){
        nb++;

        // Get the current font and apply it to hidden span tester
        var fontSize=$(this).css("font-size");
        spanTest.css("font-size", fontSize);
        var fontStyle=$(this).css("font-style");
        spanTest.css("font-style", fontStyle);
        var fontWeight=$(this).css("font-weight");
        spanTest.css("font-weight", fontWeight);
        var fontFamily=$(this).css("font-family");
        spanTest.css("font-family", fontFamily);

        // build a bench-mark to gauge it from
        var roomWidth = $(this).innerWidth();

        // now, get the width and play with it until it fits (if it doesn't)
        var txt = $(this).text();
        var contentsWidth = getLength(txt);
        if (contentsWidth > roomWidth){ // bigger than we have to work with
            roomWidth -= getLength('...'); // work within confines of room + the ellipsis
            while (contentsWidth > roomWidth){ 
                txt = txt.substring(0,txt.length-1);
                contentsWidth = getLength(txt);
            }

            // set the text to this
            $(this).text(txt).append($('<span>').text('...'));
        }
    });

    }

  //]]> 

  </script>
</head>
<body>
      <div class="backg"><div class="preview">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div></div>
      (... repeat 1000 times ...)
      <div class="backg"><div class="preview">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div></div>

</body>
</html>

!

+2

Source: https://habr.com/ru/post/1782719/


All Articles