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

时间:2018-02-05 20:08:37

标签: javascript html overflow

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中强硬,应该吗?我没有在网上看到这样的东西,也无法理解这个问题......

2 个答案:

答案 0 :(得分:1)

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

  • 获取要拆分的文本并将其存储到变量
  • 将文本拆分为多个单词(单词)
  • 逐字添加到第一个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]);
    }

答案 1 :(得分:1)

我的回答很大程度上基于Fuzzzzel巧妙地思考迭代每个单词并将它们添加到第一个元素直到它溢出。一般来说,这样的过程非常缓慢,会影响用户体验,(如果文字是10000字),但这是我能想到的唯一可行方式。

我的回答有何不同:

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

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

    < / LI>
  3. 此答案比Fuzzzzel的答案稳定~100x

  4. <强>代码:

    /* ----- 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