javascript - 将 div 拆分为每个 div 具有最大高度的 div

标签 javascript jquery css split

试图找出一种方法将一个 div 拆分为单独的 div,高度为 500 像素。到目前为止下面的代码。有什么提示吗?

<div id="test"> LOTS of TEXT WITH HEIGHT OVER 500PX</div>

查询

if($("#test").height()>500){
    //Split div into divs of 500 pix

}

编辑:
div区域是固定宽度的。我在分页功能中使用它,需要处理 div 比页面长并且需要拆分成几个较小的 div 才能在分页功能中工作的情况

最佳答案

不确定它是否性能卓越,但一种方法(或希望给您一个想法)是:

  • 迭代元素的 TextNode 个字符
  • 在每个字符处计算Rangey boundingClientRect().bottom
  • 将您的 pages 数组填充到派生自 floor(y/breakAtY)index
  • 返回一个包含分页断点文本的数组

使用 100px 作为分页符的示例:

function paginate(el, breakAtY) {
  const pages = [],
    elY = el.getBoundingClientRect().top,
    node = el.childNodes[0], // TextNode
    text = el.textContent,
    len = text.length,
    rng = document.createRange();

  for (var c = 0; c < len; c++) {
    rng.setStart(node, c);
    const i = ~~((rng.getBoundingClientRect().bottom - elY) / breakAtY);
    pages[i] = (pages[i] || '') + text[c];
  }
  return pages;
}


const myPages = paginate(document.getElementById("demo"), 100);
console.log(myPages); // Array of three pages text
#demo { font-size: 1.2em; width: 300px; }
<div id="demo">Example using 100px height pagination - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque consequatur rerum, quia placeat praesentium, sapiente eos qui omnis ratione repellendus accusamus, voluptates quos corrupti recusandae officiis quam rem, sint at. Iusto omnis, quas facere neque delectus aliquam, eligendi quibusdam ea. Inventore vitae aspernatur nihil est obcaecati rerum cupiditate sequi nemo temporibus fugiat.</div>

注意:根据要求,以上内容用于仅将 TextNode 作为其唯一子节点的元素(无内部元素!)

关于javascript - 将 div 拆分为每个 div 具有最大高度的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902739/

相关文章:

php - 如何更改 WooCommerce 上产品的外观?

javascript - 参数 'href' 应该代表 facebook 中的有效 URL

javascript - 使用 javascript 从浏览器检索用户名/密码

javascript - 在 Doubleclick for Publishers (SB) iframe 外部创建 jQuery 对话框

html - 在 HTML 中缩放图像

php - 提交联系表单并使用 validate.js

javascript - 使用 JavaScript 从 HTML 表格中获取特定的单元格值

javascript - 避免 jquery 中二分类切换的最佳实践

javascript - jQuery .mouseover() (.mouseout) div 闪烁

javascript - 尽管有值,HTML 输入字段仍返回空白