如何使用 JavaScript 将 HTML 段落拆分为其文本行

How to split an HTML paragraph up into its lines of text with JavaScript

是否有可能(以及我如何才能)将一段文本拆分为 JavaScript 各自的行。我想做的是在段落或块引用的每一行实现悬挂标点符号,而不仅仅是起始行。

也欢迎任何其他想法!

澄清 我被要求对 "split a paragraph into its respective lines" 的含义不那么含糊。

在 HTML 中,一个 <p> 元素创建了一个文本块。同样,许多其他元素也是如此。这些文本正文被换行以适合宽度(无论该宽度是由 css 设置还是由默认设置假定)我似乎无法使用正则表达式或任何其他方式检测换行符发生的位置。所以假设一个段落最终有 7 行长,我希望能够检测到它有 7 行,以及这些行的开始和结束位置。

寻找 \n\r 似乎没有任何结果。

看起来像 hanging-punctuation css property only makes sure that any punctuation at the start of the first formatted line of an element hangs. So you would want to dynamically split the text into lines of the correct length, throw those into new <p> elements (or blockquotes) & apply hanging-punctuation: 'first' to those new elements. As of right now no major browser supports the hanging-punctuation property (citation)。

通常我会建议检查换行符 (\n) 在文本中的位置,但大多数情况下没有人明确地将其放入他们编写的文本中。相反,他们让浏览器根据 window 大小(类似于自动换行)决定在何处添加新行。当您开始考虑给定 [=11= 中可能有多行时,这会变得更加棘手] 元素,并且根据浏览器的大小 window,该行可以在任何地方拆分。您必须抓取文本,找到其容器的宽度,并以某种方式查看文本字符串中达到该宽度的位置。 Heres a great blogpost 讨论了如何在更一般的意义上实现这一点。

一种蛮力的方法是将段落中的所有单词拆分成 span 个。然后,您可以测量跨度的 offsetTop 属性,以找出哪些跨度最终出现在不同的行中。

在下面的代码片段中,getLines() returns 一个数组数组,其中每个内部数组都是一个包含一行中每个单词的跨度元素。然后,您可以根据需要使用一些 CSS 创建悬挂标点符号来操纵它,也许可以通过用标点符号插入绝对定位的跨度。

//So it runs after the animation
setTimeout(function(){
    splitLines();
    showLines();
}, 1000)

function showLines() {
  var lines = getLines();
  console.log(
    lines.map(function(line) {
      return line.map(function(span) {
        return span.innerText;
      }).join(' ')
    }));
}

function splitLines() {
  var p = document.getElementsByTagName('p')[0];
  p.innerHTML = p.innerText.split(/\s/).map(function(word) {
    return '<span>' + word + '</span>'
  }).join(' ');
}



function getLines() {
  var lines = [];
  var line;
  var p = document.getElementsByTagName('p')[0];
  var words = p.getElementsByTagName('span');
  var lastTop;
  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    if (word.offsetTop != lastTop) {
      lastTop = word.offsetTop;
      line = [];
      lines.push(line);
    }
    line.push(word);
  }
  return lines;
}
<p>Here is a paragraph that we want to track lines for. Here is a paragraph that we want to track lines for. Here is a paragraph that we want to track lines for Here is a paragraph that we want to track lines for Here is a paragraph that we want to track
  lines for Here is a paragraph that we want to track lines for</p>

这是一个 fiddle,您可以调整 window 的大小,从而改变段落的大小 http://jsfiddle.net/4zs71pcd/1/