【问题标题】:Is there a way to make the height of new line characters (\n) be less than the line-height of the text?有没有办法使换行符(\n)的高度小于文本的行高?
【发布时间】:2021-05-15 15:42:45
【问题描述】:

我正在构建一个阅读器来显示文本,文本中带有\n\n 字符,当以 HTML 呈现时,它使空行的高度比我想要的要大。有没有办法控制Html中产生的空行的高度,而不用Html标签替换它们?

提前致谢。

【问题讨论】:

  • 能否请您添加一个代码示例,它可以帮助其他人以有效的方式帮助您
  • @AyushSharma,我没有代码示例,因为我不知道它是否可能。

标签: javascript html css text


【解决方案1】:

您可以通过将空行替换为空的 HTML 元素来实现:

const text = `this is an example
of multiline text.
spacing between these lines
is consistent, but line below will be different

even multiple empty lines:







will have the same height`;

const div = document.getElementById("main");
div.textContent = text;
div.innerHTML = div.innerHTML.replace(/([\n]{2,})/g, "<p>$1</p>");

console.log("original text length: ", text.length);
console.log("text from html length: ", div.textContent.length);
console.log("are both texts equal? ", div.textContent === text);
div
{
  white-space: pre;
  line-height: 2em;
}

p
{
  height: 2em;
  margin: 0;
  padding: 0;
  border: none;
  line-height: 0;
  visibility: hidden;
  white-space: none;
}
&lt;div id="main"&gt;&lt;/div&gt;

【讨论】:

  • 谢谢你的回答,但是很抱歉我忘记在注释中添加,我不想在文本中引入HTML元素,因为我必须做一些选择并且能够知道偏移量正确选择的文本。包含 HTML 元素会给出不正确的结果,对吗?
  • 我已经更新了显示原始文本与 HTML 中的文本相同的代码。
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2011-01-09
相关资源
最近更新 更多