从字符串中获取 x 像素文本的最可靠方法,javascript

发布于 2024-10-15 22:40:15 字数 2642 浏览 4 评论 0 原文

我的 JavaScript 文件中有一个包含大量文本 text 的字符串。我还有一个元素 div#container ,它的样式(使用单独的 CSS)具有潜在的非标准 line-heightfont-size、< code>font-face,也许还有其他。它有固定的高度和宽度。

我想获得可以容纳 div#container 的最大文本量,而不会从字符串中溢出。这样做的最佳方法是什么?

这需要能够使用标签格式化的文本,例如:

<strong>Hello person that is this is long and may take more than a</strong> 
line and so on.

目前,我有一个适用于纯文本的 JQuery 插件,代码如下:

// returns the part of the string that cannot fit into the object
$.fn.func = function(str) {
    var height = this.height();

    this.height("auto");
    while(true) {
        if(str == "") {
            this.height(height);
            return str; // the string is empty, we're done
        }

        var r = sfw(str); // r = [word, rest of String] (sfw is a split first word function defined elsewhere
        var w = r[0], s = r[1];

        var old_html = this.html();
        this.html(old_html + " " + w);

        if(this.height() > height)
        {
            this.html(old_html);
            this.height(height);
            return str; // overflow, return to last working version
        }

        str = s;

    }
}

更新:

数据如下所示:

<ol>
  <li>
     <h2>Title</h2>
     <ol>
        <li>Character</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
     <ol>
        <li>This can be split from other</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
   </li>  <li>
     <h2>Title</h2>
     <ol>
        <li>Character</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
     <ol>
        <li>This can be split from other</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
   </li>
</ol>

I have a string which contains a lot of text, text, in my JavaScript file. I also have an element, div#container that is styled (using separate CSS) with potentially nonstandard line-height, font-size, font-face, and maybe others. It has a fixed height and width.

I'd like to get the maximum amount of text that can fit into div#container without any overflow from the string. What's the best way of doing this?

This needs to be able to work with text formatted with tags, for example:

<strong>Hello person that is this is long and may take more than a</strong> 
line and so on.

Currently, I've got a JQuery plugin that works for plain text, code follows:

// returns the part of the string that cannot fit into the object
$.fn.func = function(str) {
    var height = this.height();

    this.height("auto");
    while(true) {
        if(str == "") {
            this.height(height);
            return str; // the string is empty, we're done
        }

        var r = sfw(str); // r = [word, rest of String] (sfw is a split first word function defined elsewhere
        var w = r[0], s = r[1];

        var old_html = this.html();
        this.html(old_html + " " + w);

        if(this.height() > height)
        {
            this.html(old_html);
            this.height(height);
            return str; // overflow, return to last working version
        }

        str = s;

    }
}

UPDATE:

The data looks like this:

<ol>
  <li>
     <h2>Title</h2>
     <ol>
        <li>Character</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
     <ol>
        <li>This can be split from other</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
   </li>  <li>
     <h2>Title</h2>
     <ol>
        <li>Character</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
     <ol>
        <li>This can be split from other</li>
        <ol>
          <li>Line one that might go on a long time, SHOULD NOT BE BROKEN</li>
          <li>Line two can be separated from line one, but not from itself</li>
        </ol>
      </ol>
   </li>
</ol>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

燃情 2024-10-22 22:40:15

好吧,让我尝试解决它;)实际上在考虑解决方案时,我注意到我对您的需求了解不够,所以我决定开发简单的 JavaScript 代码并向您展示结果;尝试后你可以告诉我出了什么问题,以便我可以修复/更改它,好吗?

我使用纯 JavaScript,没有 jQuery(如果需要可以重写)。原理和你的jQuery插件类似:如果

  1. 它是开始标签的一部分,我们会一一获取字符(而不是像sfw函数那样的单词;它可以更改),
  2. 如果它是开始标签的一部分,浏览器不会显示它,所以我没有以特殊的方式处理它,只是从标签名称中一一附加字符并检查容器的高度......不知道它是否那么糟糕。我的意思是,当我在浏览器中编写 container.innerHTML = "My String has a link 时,我会看到“My String has a link” ,因此“未完成”标签不会影响容器的大小(至少在我测试的所有浏览器中)
  3. 检查容器的大小,如果它比我们预期的大,则前一个字符串(实际上是没有最后一个字符的当前字符串)就是我们现在要寻找的,
  4. 我们必须关闭所有开始标签,这些标签没有关闭是因为剪切

HTML 页面来测试它:

<html>

  <head>
    <style>
    div {
      font-family: Arial;
      font-size: 20px;
      width: 200px;
      height: 25px;
      overflow: hidden;
    }
    </style>
  </head>

  <body>
     <div id="container"> <strong><i>Strong text with <a href="#">link</a> </i> and </strong> simple text </div>

     <script>
     /**
      * this function crops text inside div element, leaving DOMstructure valid (as much as possible ;).
      * also it makes visible part as "big" as possible, meaning that last visible word will be split 
      * to show its first letters if possible
      *
      * @param container {HTMLDivElement} - container which can also have html elements inside
      * @return {String} - visible part of html inside div element given
      */
     function cropInnerText( container ) {
       var fullText = container.innerHTML; // initial html text inside container 
       var realHeight = container.clientHeight; // remember initial height of the container 
       container.style.height = "auto"; // change height to "auto", now div "fits" its content 

       var i = 0;
       var croppedText = "";
       while(true) {
         // if initial container content is the same that cropped one then there is nothing left to do
         if(croppedText == fullText) { 
           container.style.height = realHeight + "px";
           return croppedText;
         }

         // actually append fullText characters one by one...    
         var nextChar = fullText.charAt( i );
         container.innerHTML = croppedText + nextChar;  

         // ... and check current height, if we still fit size needed
         // if we don't, then we found that visible part of string
         if ( container.clientHeight > realHeight ) {
           // take all opening tags in cropped text 
           var openingTags = croppedText.match( /<[^<>\/]+>/g );
           if ( openingTags != null ) {
             // take all closing tags in cropped text 
             var closingTags = croppedText.match( /<\/[^<>]+>/g ) || [];
             // for each opening tags, which are not closed, in right order...
             for ( var j = openingTags.length - closingTags.length - 1; j > -1; j-- ) {
               var openingTag; 
               if ( openingTags[j].indexOf(' ') > -1 ) {
                 // if there are attributes, then we take only tag name
                 openingTag = openingTags[j].substr(1, openingTags[j].indexOf(' ')-1 ) + '>';
               }
               else {
                 openingTag = openingTags[j].substr(1);
               }
               // ... close opening tag to have valid html
               croppedText += '</' + openingTag;
             }
           }

           // return height of container back ... 
           container.style.height = realHeight + "px";
           // ... as well as its visible content 
           container.innerHTML = croppedText;
           return croppedText;
         }

         i++;
         croppedText += nextChar;
       }

     }

     var container = document.getElementById("container");
     var str = cropInnerText( container );
     console.info( str ); // in this case it prints '<strong><i>Strong text with <a href="#">link</a></i></strong>'
   </script>

</body>

可能的改进/更改:

  1. 我不创建任何新的 DOM 元素,因此我只是重用当前容器(以确保我考虑到所有 css 样式);这样我就可以一直更改其内容,但是在获取可见文本后,如果需要,您可以将 fullText 写回到容器中(我也不会更改)
  2. 逐字处理原始文本将使我们更少DOM 的变化(我们将逐字写入而不是逐字符写入),因此这种方式应该更快。您已经拥有 sfw 函数,因此您可以轻松更改它。
  3. 如果我们有两个单词“ourentence”,则可见的可能只是第一个(“our”),并且“sentence”应该被删除( >overflow:hidden 将以这种方式工作)。就我而言,我将逐个字符附加,因此我的结果可以是“我们发送的”。同样,这不是算法的复杂部分,因此根据您的 jQuery 插件代码,您可以更改我的以处理单词。

欢迎提出问题、评论、发现的错误;)我在 IE9、FF3.6、Chrome 9 中测试了它

更新: 根据


  • ...例如,我有包含内容的容器:

  • <div id="container"> <strong><i>Strong text with <ul><li>link</li></ul> </i> and </strong> simple text </div>
    

    在这种情况下,浏览器的行为方式如下(容器中的字符串和我看到的内容根据算法显示):

    ...
    "<strong><i>Strong text with <" -> "<strong><i>Strong text with <"
    "<strong><i>Strong text with <u" -> "<strong><i>Strong text with "
    "<strong><i>Strong text with <ul" -> "<strong><i>Strong text with <ul></ul>" // well I mean it recognizes ul tag and changes size of container
    

    算法的结果是字符串 "< ;strong>带有 " 的强文本 - 带有 ",有什么不好的。在这种情况下我需要处理的是,如果我们找到结果字符串(根据算法"Strong text with ),我们需要删除最后一个“未关闭”标签(在我们的例子中为 " ),因此在关闭标签以获得有效的 html 之前,我添加了以下内容:

    ...
    if ( container.clientHeight > realHeight ) {
      /* start of changes */
      var unclosedTags = croppedText.match(/<[\w]*/g);
      var lastUnclosedTag = unclosedTags[ unclosedTags.length - 1 ];
      if ( croppedText.lastIndexOf( lastUnclosedTag ) + lastUnclosedTag.length == croppedText.length ) {
        croppedText = croppedText.substr(0, croppedText.length - lastUnclosedTag.length );
      }
      /* end of changes */
      // take all opening tags in cropped text 
    ...
    

    可能有点懒惰的实现,但如果速度减慢,可以对其进行调整向下。这里所做的就是

    1. 获取所有不带 > 的标签(在我们的例子中,它返回 [") ;
    2. 取最后一个("),
    3. 如果它是croppedText字符串的末尾,那么我们

    做完后将其删除,结果字符串变成"< strong>带有"的强文本

    UPDATE2 例如,谢谢您,所以我发现您不仅仅有嵌套标签,但它们也有“树”结构,确实我没有考虑到它,但它仍然可以修复;)一开始我想写我合适的“解析器”,但当我总是得到一个例子不起作用,所以我认为最好找到已经编写的解析器,有一个: 纯 JavaScript HTML 解析器。还有一个粗暴

    虽然这个库不涵盖
    全部可能的奇怪之处
    HTML 提供了,它确实处理了很多
    最明显的东西。

    但对于你的例子来说它是有效的;该库没有考虑开始标签的位置,但

    1. 我们相信原始的 html 结构很好(没有损坏);
    2. 我们在结果“字符串”的末尾关闭标签(所以这是可以的)

    我认为有了这个假设,这个库就很好用。那么结果函数如下所示:

    <script src="http://ejohn.org/files/htmlparser.js"></script>
     <script>
     function cropInnerText( container ) {
       var fullText = container.innerHTML;
       var realHeight = container.clientHeight;
       container.style.height = "auto";
    
       var i = 0;
       var croppedText = "";
       while(true) {
         if(croppedText == fullText) { 
           container.style.height = realHeight + "px";
           return croppedText;
         }
    
         var nextChar = fullText.charAt( i );
         container.innerHTML = croppedText + nextChar;  
    
         if ( container.clientHeight > realHeight ) {
           // we still have to remove unended tag (like "<u" - with no closed bracket)
           var unclosedTags = croppedText.match(/<[\w]*/g);
           var lastUnclosedTag = unclosedTags[ unclosedTags.length - 1 ];
           if ( croppedText.lastIndexOf( lastUnclosedTag ) + lastUnclosedTag.length == croppedText.length ) {
             croppedText = croppedText.substr(0, croppedText.length - lastUnclosedTag.length );
           }
    
           // this part is now quite simple ;)
           croppedText = HTMLtoXML(croppedText);
    
           container.style.height = realHeight + "px";
           container.innerHTML = croppedText ;
           return croppedText;
         }
    
         i++;
         croppedText += nextChar;
       }
    
     }
     </script>
    

    well, let me try to solve it ;) actually thinking about solution I noticed that I don't know enough about requirements you have, so I decided to develop simple JavaScript code and show you result; after trying it you can tell me what's wrong so I can fix/change it, deal?

    I used pure JavaScript, no jQuery (it can be rewritten if needed). The principle is similar to your jQuery plugin:

    1. we take characters one by one (instead of words as sfw function does; it can be changed)
    2. if it is part of opening tag, browser does not show it, so I didn't processed it special way, just appended one by one characters from tag name and checked height of container... no idea if it is that bad. I mean when I write container.innerHTML = "My String has a link <a href='#'"; in browser I see "My String has a link", so "unfinished" tag does not influence size of container (at least in all browsers where I tested)
    3. check size of container, and if it is bigger than we expect it to be, then previous string (actually current string without last character) is what we are looking for
    4. now we have to close all opening tags, which are not closed because of cutting

    HTML page to test it:

    <html>
    
      <head>
        <style>
        div {
          font-family: Arial;
          font-size: 20px;
          width: 200px;
          height: 25px;
          overflow: hidden;
        }
        </style>
      </head>
    
      <body>
         <div id="container"> <strong><i>Strong text with <a href="#">link</a> </i> and </strong> simple text </div>
    
         <script>
         /**
          * this function crops text inside div element, leaving DOMstructure valid (as much as possible ;).
          * also it makes visible part as "big" as possible, meaning that last visible word will be split 
          * to show its first letters if possible
          *
          * @param container {HTMLDivElement} - container which can also have html elements inside
          * @return {String} - visible part of html inside div element given
          */
         function cropInnerText( container ) {
           var fullText = container.innerHTML; // initial html text inside container 
           var realHeight = container.clientHeight; // remember initial height of the container 
           container.style.height = "auto"; // change height to "auto", now div "fits" its content 
    
           var i = 0;
           var croppedText = "";
           while(true) {
             // if initial container content is the same that cropped one then there is nothing left to do
             if(croppedText == fullText) { 
               container.style.height = realHeight + "px";
               return croppedText;
             }
    
             // actually append fullText characters one by one...    
             var nextChar = fullText.charAt( i );
             container.innerHTML = croppedText + nextChar;  
    
             // ... and check current height, if we still fit size needed
             // if we don't, then we found that visible part of string
             if ( container.clientHeight > realHeight ) {
               // take all opening tags in cropped text 
               var openingTags = croppedText.match( /<[^<>\/]+>/g );
               if ( openingTags != null ) {
                 // take all closing tags in cropped text 
                 var closingTags = croppedText.match( /<\/[^<>]+>/g ) || [];
                 // for each opening tags, which are not closed, in right order...
                 for ( var j = openingTags.length - closingTags.length - 1; j > -1; j-- ) {
                   var openingTag; 
                   if ( openingTags[j].indexOf(' ') > -1 ) {
                     // if there are attributes, then we take only tag name
                     openingTag = openingTags[j].substr(1, openingTags[j].indexOf(' ')-1 ) + '>';
                   }
                   else {
                     openingTag = openingTags[j].substr(1);
                   }
                   // ... close opening tag to have valid html
                   croppedText += '</' + openingTag;
                 }
               }
    
               // return height of container back ... 
               container.style.height = realHeight + "px";
               // ... as well as its visible content 
               container.innerHTML = croppedText;
               return croppedText;
             }
    
             i++;
             croppedText += nextChar;
           }
    
         }
    
         var container = document.getElementById("container");
         var str = cropInnerText( container );
         console.info( str ); // in this case it prints '<strong><i>Strong text with <a href="#">link</a></i></strong>'
       </script>
    
    </body>
    

    Possible improvements / changes:

    1. I do not create any new DOM elements, so I just reuse current container (to be sure I take into account all css styles); this way I change its content all the time, but after taking visible text you can write fullText back into container if needed (which I also do not change)
    2. Processing original text word by word will let us make less changes in DOM (we will write word by word instead of character by character), so this way should be faster. You already have sfw function, so you can change it easily.
    3. If we have two words "our sentence", it is possible that visible will be only first one ("our"), and "sentence" should be cut (overflow:hidden will work this way). In my case, I will append character by character, so my result can be "our sent". Again, this is not a complex part of algorithm, so based on your jQuery plugin code, you can change mine to work with words.

    Questions, remarks, bugs found are welcome ;) I tested it in IE9, FF3.6, Chrome 9

    UPDATE: Accroding to an issue with <li>, <h1> ... E.g. I have container with content:

    <div id="container"> <strong><i>Strong text with <ul><li>link</li></ul> </i> and </strong> simple text </div>
    

    In this case browser behaves this way (string by string what is in container and what I see it shows according to the algorithm):

    ...
    "<strong><i>Strong text with <" -> "<strong><i>Strong text with <"
    "<strong><i>Strong text with <u" -> "<strong><i>Strong text with "
    "<strong><i>Strong text with <ul" -> "<strong><i>Strong text with <ul></ul>" // well I mean it recognizes ul tag and changes size of container
    

    and result of algorithm is string "<strong><i>Strong text with <u</i></strong>" - with "<u", what is not nice. What I need to process in this case is that if we found our result string ("<strong><i>Strong text with <u" according to the algorithm), we need to removed last "unclosed" tag ("<u" in our case), so before closing tags to have valid html I added the following:

    ...
    if ( container.clientHeight > realHeight ) {
      /* start of changes */
      var unclosedTags = croppedText.match(/<[\w]*/g);
      var lastUnclosedTag = unclosedTags[ unclosedTags.length - 1 ];
      if ( croppedText.lastIndexOf( lastUnclosedTag ) + lastUnclosedTag.length == croppedText.length ) {
        croppedText = croppedText.substr(0, croppedText.length - lastUnclosedTag.length );
      }
      /* end of changes */
      // take all opening tags in cropped text 
    ...
    

    probably a bit lazy implementation, but it can be tuned if it slows down. What is done here

    1. take all tags without > (in our case it returns ["<strong", "<i", "<u"]);
    2. take last one ("<u")
    3. if it is end of croppedText string, then we remove it

    after doing it, the result string becomes "<strong><i>Strong text with </i></strong>"

    UPDATE2 thank you for example, so I see that you don't have just nested tags, but they also have "tree" structure, indeed I didn't take it into account, but it still can be fixed ;) At the beginning I wanted to write my appropriate "parser", but all the time I get an example when I does not work, so I thought it is better to find already written parser, and there is one: Pure JavaScript HTML Parser. There is also one shag to it:

    While this library doesn't cover the
    full gamut of possible weirdness that
    HTML provides, it does handle a lot of
    the most obvious stuff.

    but for your example it works; that library didn't take into account position of opening tag, but

    1. we rely that original html structure is fine (not broken);
    2. we close tags at the end of the result "string" (so this is ok)

    I think that with that assumptions this library is nice to use. Then result function looks like:

    <script src="http://ejohn.org/files/htmlparser.js"></script>
     <script>
     function cropInnerText( container ) {
       var fullText = container.innerHTML;
       var realHeight = container.clientHeight;
       container.style.height = "auto";
    
       var i = 0;
       var croppedText = "";
       while(true) {
         if(croppedText == fullText) { 
           container.style.height = realHeight + "px";
           return croppedText;
         }
    
         var nextChar = fullText.charAt( i );
         container.innerHTML = croppedText + nextChar;  
    
         if ( container.clientHeight > realHeight ) {
           // we still have to remove unended tag (like "<u" - with no closed bracket)
           var unclosedTags = croppedText.match(/<[\w]*/g);
           var lastUnclosedTag = unclosedTags[ unclosedTags.length - 1 ];
           if ( croppedText.lastIndexOf( lastUnclosedTag ) + lastUnclosedTag.length == croppedText.length ) {
             croppedText = croppedText.substr(0, croppedText.length - lastUnclosedTag.length );
           }
    
           // this part is now quite simple ;)
           croppedText = HTMLtoXML(croppedText);
    
           container.style.height = realHeight + "px";
           container.innerHTML = croppedText ;
           return croppedText;
         }
    
         i++;
         croppedText += nextChar;
       }
    
     }
     </script>
    
    友谊不毕业 2024-10-22 22:40:15

    要获得尽可能长的第一行:

    1. 创建一个带有 visibility:hidden; 的 DIV(这样它将具有尺寸),但将其定位为 position:absolute; 这样就不会中断您的页面流
    2. 将其类型样式设置为与生成的 DIV 相同的值
    3. 将其高度设置为与生成的 DIV 相同,但保留 width:auto;
    4. 向其中添加文本
    5. 继续剪切文本,直到宽度低于生成的 DIV 的宽度。

    结果是您可以输入的文本。

    如果您需要找到适合容器的数量以保持height:auto;并设置固定,请调整算法>宽度

    自动调整文本区域也使用了相同的技术,这些文本区域在用户输入文本时自动增长。

    To get longest possible first line:

    1. Create a DIV with visibility:hidden; (so it will have dimension) but position it as position:absolute; so it won't break your page flow
    2. set its type style to the same values as your resulting DIV
    3. Set it's height the same as resulting DIV but keep width:auto;
    4. Add text to it
    5. Keep cutting off text until width drops below resulting DIV's width.

    The result is the text you can put in.

    Adjust the algorithm if you need to find amount of lines that fit into container to keep height:auto; and set fixed width.

    The same technique is used by auto-adjusting textareas that auto-grow while users type in text.

    々眼睛长脚气 2024-10-22 22:40:15

    为了解决这个问题,您将需要额外的信息:

    1. 我应该在哪里“切割”已切割的输入文本
    2. ,如何修复两半以便我可以将每一半填充到 DIV 中?

    至于“在哪里切割”问题,您可能必须在输入字符串中的战略点处注入唯一的 锚标记(例如...在输入中的每个开始标记之前?)。然后,您可以测试每个锚点的布局位置并找到中断输入的位置。

    找到最符合逻辑的中断点后,您需要在前半部分的末尾添加标签以将其关闭,并在下半部分的前面添加标签以将其打开。因此,当您之前解析输入字符串以查找开始标记时,您在注入 时保留了“标记堆栈”列表。查找与此特定相关的标签堆栈,然后根据需要添加标签。

    我可以发现两个陷阱:

    1. 如果输入标签具有属性,您将需要保留有关每个中断的更多信息,
    2. 您可能需要将某些标签视为“牢不可破”并在较早的 处中断。 相反

    ,最终,在我看来,您正在等待 HTML5 的列构造。

    To solve this, you're going to need additional information:

    1. where should I 'chop' the input text
    2. having chopped it, how do I repair the two halves so that I can stuff each one into a DIV?

    As for the 'where to chop' question, you'll probably have to inject unique <a name="uniq"/> anchor tags at strategic points in your input string (say ... before each opening tag in the input?). Then, you can test the layed-out position of each anchor and find where to break the input.

    Having found the most logical point to break, you'll need to add tags at the end of the first half to close it off, and add tags at the front of the next half to open it. So when you parsed your input string to find the opening tags previously, you kept a list of the 'tag stack' when you injected the <a/>. Lookup the tag stack that's relevant for this paritcular and then add the tags as required.

    I can spot 2 gotchas with this:

    1. you'll need to keep more information about each break if the input tags have attributes
    2. you may need to treat some tags as 'unbreakable' and break at an earlier <a/> instead

    Ultimately, it seems to me you're waiting for HTML5's column construct.

    原来是傀儡 2024-10-22 22:40:15

    您是否只是想格式化段落中的第一行? CSS :first-line 伪选择器是否有效适合您的应用程序?

    Are you just trying to format the first line in a paragraph? Would the CSS :first-line pseudo-selector work for your application?

    洛阳烟雨空心柳 2024-10-22 22:40:15

    您可以使用 getCompulatedStyle 来找出内联元素的宽度(即它有display: inline 属性):

    window.getComputedStyle(element, null).getPropertyValue("width");
    

    如果发现该元素的宽度大于其容器的宽度,您将逐步删除一些文本,直到它适合为止。

    You could use getComputedStyle to find out the width of an inline element (i.e. it has the display: inline property):

    window.getComputedStyle(element, null).getPropertyValue("width");
    

    If it turns out that this element's width is larger than its container's width, you would remove some text step by step until it fits in.

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文