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

标签 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 来检测我的段落中是否存在文本溢出(高度是固定的)。但更具体地说,我想做的是,如果滚动高度大于偏移高度,则在另一个 <div> 上显示溢出的文本部分。 。 (在此示例中为 element2)。在 javascript 中应该不难,不是吗?我在网上没有见过这样的东西,无法理解这个问题......

最佳答案

我的答案很大程度上基于 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 毫秒
    • 87.778076171875 毫秒
    • 89.469726562500 毫秒
    • 77.690673828125 毫秒
    • 62.181152343750 毫秒
  2. Fuzzzzel 的回答( jsFiddle used ):

    • 8468.773193359375 毫秒
    • 8544.271972656250 毫秒
    • 9054.047851562500 毫秒
    • 8470.183837890625 毫秒
    • 8730.039306640625 毫秒

关于javascript - 在另一个div上显示溢出的文本部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630652/

相关文章:

javascript - 在组件内部使用 React 链接图像

javascript - 如何将对象作为数据类型传递给sequelize中的数据模型?

javascript - 无法使用Google云功能将数据保存到Firestore

javascript - CSS 帮助 - 移动网站的页脚

javascript - 使用溢出时隐藏滚动条 :scroll; but keep scrolling ability

html - Windows Phone 8 IE10 Mobile 溢出滚动不起作用

javascript - Gulp 4 Watch Task,只运行一次

javascript - 使用 vanilla javascript 将 es6 模板字符串转换为 html 元素

php - 在页面加载时从目录加载随机图像(没有文件名列表)

html - z-index 不适用于溢出重叠和滚动条