Javascript - 如何统计一个div每行的字符数

3
我正在设计我的网站,但在排版方面遇到了困难。我希望能够知道段落div中每行有多少个字符。是否可以使用Javascript或jQuery实现这一点?
例如:我有一个720像素宽的div,字体大小为18像素,如何计算每行有多少个字符?如果可行,我还想了解如何计算空格或从计数中排除它们。
我目前正在使用$("#mydiv p").text().length,但它会计算所有字符,而不是每行的字符。
感谢您的帮助和回复。

document.write( $("#mydiv p").text().length );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="mydiv" style="font-size: 18px; width: 720px; border: 1px solid red;">
<p>This is my div! This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!This is my div!</p>
</div>


请明确您要解决的问题。除非您使用等宽字体,否则计算字符是毫无意义的。 - user5734311
感谢您的评论。我想遵循排版规则,即每段最佳长度应包含每行 45-75 个字符。为此,我正在寻找一种 JS 解决方案,以允许我计算每行有多少个字符,并确定设置 div 的宽度。 - Snorlax
我不确定这是否可能。如果您使用的是等宽字体(每个字符的宽度相同),那么只需要进行一些简单的数学计算(div宽度/字符宽度)。但是对于变宽字体,我能想到的唯一方法是在特定间隔处以编程方式添加换行符,但这并不是您要实现的目标。 - Lissy93
谢谢您的评论。我使用PT Serif字体,不知道是否有所不同。 - Snorlax
有一个 em 单位,它是 M 字符的宽度。尝试使用 40em 这样的宽度:https://jsfiddle.net/ap8bn0su/ - user5734311
1个回答

0

如果您只需要设置每行一个字符的限制,只需使用ch单位即可:

.max720{
  width:720px;
  font-size:18px;
}

.max50ch p{
max-width:50ch;
}
<div class="max720 max50ch">
  <p><strong>Max 50 characters per line.</strong> One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p>

<p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p>
  </div>

示例2:每行字符计数

如果您需要获取每行的确切字符计数,则需将文本内容拆分为字符数组,并检查该行的offsetHeight

let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(function (paragraph, p) {
  let text = paragraph.textContent;
  //split to character array
  let textArr = text.split("");
  //append temporary span element
  let line = document.createElement("span");
  paragraph.insertBefore(line, paragraph.firstChild);
  let charCount = 0;
  let charArr = [];
  let lineNo = 1;
  let lineY = line.offsetHeight;

  textArr.forEach(function (char, i) {
   //add text character by character
    line.textContent += char;
    charCount++;
    let currentY = line.offsetHeight;
    //currentY > lineY = new line
    if (currentY > lineY || i == textArr.length - 1) {
      let charPerLine = charCount - 1;
      console.log(`paragraph ${p+1};  line ${lineNo}: ${charPerLine} characters`);
      lineY = currentY;
      charCount = 0;
      lineNo++;
    }
  });
  //remove span
  line.remove();
});
.max720{
  width:720px;
  font-size:18px;
}
<div class="max720 max72ch">
  <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.</p>

<p>The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.</p>
  </div>


谢谢你的帮助,它很好地工作了。我非常感激。有一个疑问,我想只计算具有特定ID的段落p,我该如何做到这一点? - Snorlax
1
只需将初始选择器更改为以下内容:let paragraphs = document.querySelectorAll("#customParagraph")。但很可能您应该使用类来避免重复的ID引用(并使用#id选择器样式化这些段落-特异性核弹!) - herrstrietzel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接