在另一个 div 上显示溢出的文本部分

Display the part of the text in overflow on another div

HTML

<div id="element1"><p id="hello">test test test test ... test test test test</p></div>
<div id="element2"><p></p></div>

JAVASCRIPT

var element = document.querySelector('#element1');
if( (element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
   // my element have overflow
  element.style.background = "yellow";
}
else{
  //my element don't have overflow
}

我用那个简单的javascript来检测我的段落中是否有文字溢出(高度是固定的)。但更具体地说,我想要做的是,如果 scrollheight 大于 offsetheight,则在另一个 <div> 上显示溢出的文本部分。 (在这个例子中是 element2)。在 javascript 应该不难吧?我没有在网上看到过这样的东西,也无法理解这个问题...

将我的评论放入一些代码中:

  • 将要拆分的文本存入变量
  • 将文本拆分成多个部分(单词)
  • 逐字逐句添加到第一个 div,直到填满
  • 然后把下面的话加到另一个div

这是我使用您的 html:

想出的代码片段
    function addWord(word) {
        // Query the divs to measure and the containing paragraph
        const element1 = document.querySelector('#element1');
        const p1 = element1.querySelector('p');
        const element2 = document.querySelector('#element2');
        const p2 = element2.querySelector('p');

        // Test if the div is full
        if ((element1.offsetHeight < element1.scrollHeight) || (element1.offsetWidth < element1.scrollWidth)) {

            // If full, add the text to second div
            p2.innerHTML += ' ' + word;
        } else {

            // If not full add the text to first div
            p1.innerHTML += ' ' + word;
        }
    }

    // Execute this part after your DOM is loaded

    // Query text you want to put into the two divs
    let text = document.querySelector('#element1 p').innerHTML;

    // Split the text into words (roughly)
    let words = text.split(' ');

    // Empty the text you just loaded
    document.querySelector('#element1 p').innerHTML = '';

    // Add the text to the divs word by word
    for (let i = 0; i < words.length; i++) {
        addWord(words[i]);
    }

我的回答主要基于 Fuzzzzel 迭代每个单词并将它们添加到第一个元素直到溢出的巧妙想法。一般来说,这样的过程很慢,会影响用户体验,(如果文本是10000个字怎么办),但这是我能想到的唯一可能的方法。

我的回答有什么不同:

  1. 我的回答尊重元素的 padding 并且如果元素已满则不会插入另一个词,而 Fuzzzzel 则不会,如图 here.

  2. 我使用 textContent 这是一种在 HTML 节点中获取和设置文本的更快方法,因为它不会尝试解析 HTML

  3. 这个答案比 Fuzzzzel 的答案稳定 ~100x 快。

代码:

/* ----- JavaScript ----- */
;(function () {
  var
    /* Cache the elements. */
    element1 = document.getElementById("element1"),
    element2 = document.getElementById("element2"),

    /* Cache the paragraphs. */
    p1 = document.querySelector("#element1 > p"),
    p2 = document.querySelector("#element2 > p"),

    /* Cache the content of element1 > p and split it at the spaces. */
    content = p1.textContent.split(/\s/),

    /* Create an array with the final content of the first paragraph. */
    p1final = [],

    /* Create a flag the signals whether the content has overflowed in element1. */
    overflowed = false;

  /* Empty the first paragraph. */
  p1.textContent = "";

  /* Iterate over every word of the content. */
  [].forEach.call(content, function (word, index) {
    /* Check whether the content has already overflowed. */
    if (overflowed) {
      /* Add the word to the second paragraph. */
      p2.textContent += (index ? " " : "") + word;
    }
    else {
      /* Define the variables. */
      var hasXOverflow, hasYOverflow;

      /* Add the word to the first paragraph. */
      p1.textContent += (index ? " " : "") + word;

      /* Cache the overflow data. */
      hasXOverflow = element1.offsetWidth < element1.scrollWidth;
      hasYOverflow = element1.offsetHeight < element1.scrollHeight;

      /* Check whether the content overflows. */
      if (hasXOverflow || hasYOverflow) {
        /* Remove the word that made the first paragraph overflow
        by using the all previous words (saved in p1final). */
        p1.textContent = p1final.join(" ");

        /* Add the word to the second paragraph. */
        p2.textContent += (index ? " " : "") + word;

        /* Set the oveflowed flag to true. */
        overflowed = true;
      }
      else {
        /* Add the word to the p1final array. */
        p1final[index] = word;
      }
    }
  });
})();

查看 this jsFiddle 或以下代码片段以获取代码演示。

片段:

/* ----- JavaScript ----- */
;(function () {
  var
    /* Cache the elements. */
    element1 = document.getElementById("element1"),
    element2 = document.getElementById("element2"),
    
    /* Cache the paragraphs. */
    p1 = document.querySelector("#element1 > p"),
    p2 = document.querySelector("#element2 > p"),
    
    /* Cache the content of element1 > p and split it at the spaces. */
    content = p1.textContent.split(/\s/),
    
    /* Create an array with the final content of the first paragraph. */
    final = [],
    
    /* Create a flag the signals whether the content has overflowed in element1. */
    overflowed = false;
    
  /* Empty the first paragraph. */
  p1.textContent = "";
  
  /* Iterate over every word of the content. */
  [].forEach.call(content, function (word, index) {
    /* Check whether the content has already overflowed. */
    if (overflowed) {
      /* Add the word to the second paragraph. */
      p2.textContent += (index ? " " : "") + word;
    }
    else {
      /* Define the variables. */
      var hasXOverflow, hasYOverflow;
        
      /* Add the word to the first paragraph. */
      p1.textContent += (index ? " " : "") + word;
      
      /* Cache the overflow data. */
      hasXOverflow = element1.offsetWidth < element1.scrollWidth;
      hasYOverflow = element1.offsetHeight < element1.scrollHeight;
      
      /* Check whether the content overflows. */
      if (hasXOverflow || hasYOverflow) {
        /* Remove the word that made the first paragraph overflow
        by using the all previous words (saved in final). */
        p1.textContent = final.join(" ");
        
        /* Add the word to the second paragraph. */
       p2.textContent += (index ? " " : "") + word;
        
        /* Set the oveflowed flag to true. */
        overflowed = true;
      }
      else {
        /* Add the word to the final array. */
        final[index] = word;
      }
    }
  });
})();
/* ----- CSS ----- */
[id ^= "element"] {
  width: 100px;
  display: inline-block;
  padding: 1em;
  vertical-align: top;
  background-color: #ccc;
  border: 1px solid #888;
}

#element1 {
  height: 150px;
  overflow: hidden;
}

p {margin: 0}
<!----- HTML ----->
<div id="element1">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
<div id="element2">
  <p></p>
</div>

速度测试结果:

(2,857 字 19,040 个字符)

  1. 这个回答(jsFiddle used):

    • 81.217041015625 ms
    • 87.778076171875 ms
    • 89.469726562500 ms
    • 77.690673828125 ms
    • 62.181152343750 ms
  2. Fuzzzzel 的回答(jsFiddle used):

    • 8468.773193359375 ms
    • 8544.271972656250 ms
    • 9054.047851562500 ms
    • 8470.183837890625 ms
    • 8730.039306640625 ms