javascript - 在多个(句子)对象上保存用户突出显示的文本

标签 javascript html reactjs text highlighting

假设我有一个文本,看起来像这样:

<span> Some sentence in which a fox jumps over some fence. </span>
<span> Another sentence in which a dog jumps over some fox. </span>
<span> Yet another one, I think you get the idea. </span>

假设用户现在选择跨越两个 <span> 的文本位项目,然后按下按钮以突出显示或加粗选择。对于用户来说,它看起来像这样:

Some sentence in which a fox jumps over some fence. Another sentence in which a dog jumps over some fox. Yet another one, I think you get the idea.

我想知道如何保存这样的东西。我通过遍历一个吐出句子的数组来创建这些跨度,但是我怎么会记得一个高亮跨越两个句子并且是一个高亮(我这样说是因为我当然可以以某种方式保存句子 2 的末尾和句子 3 的开头被突出显示,但这会将突出显示视为分开的)?

顺便说一句,我在这里使用 React。

最佳答案

您可以只使用两个单独的粗体标记,这样您就可以获得有效的 HTML,这是您提到的显而易见的解决方案。问题是您是否有任何要求不适用于此解决方案,例如在每个突出显示周围设置边框?

<span> Some sentence in which a fox jumps over some fence. </span>
<span> Another sentence in which a dog jumps <b>over some fox.</b> </span>
<span><b>Yet another</b> one, I think you get the idea. </span>

或者您可以避免将每个句子都放在一个不会增加任何值(value)的范围内的想法。取而代之的是将句子中的开始和结束标记保持在数组中,然后将它们连接起来并显示为一个段落。开始和结束标记不必是 <b>但您选择的任何标记。

const array = ["Some sentence in which a fox jumps over some fence.",
"Another sentence in which a dog jumps <b>over some fox.",
"Yet another one, </b>I think you get the idea."];

const p = document.createElement('p');
p.innerHTML = array.join('<br>');
document.body.append(p);

关于javascript - 在多个(句子)对象上保存用户突出显示的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43763946/

相关文章:

javascript - html5 canvas - 如何拉伸(stretch)文本?

javascript - 如何获取三个按钮中的两个按钮的类名称?

html - 垂直菜单导航 - 菜单滚动时不显示子菜单

javascript - javascript中的原型(prototype)行为

javascript - 是什么导致 iframe 在父窗口中打开新链接?

javascript - 使用切换关闭单独 div 上的所有其他事件类

reactjs - 使用 Nginx 向 Spotify 授权

reactjs - Jest 类型错误 : is not a constructor in Jest. 模拟

javascript - styled.TouchableOpacity 组件中 props.style 的类型是什么?

javascript - SetInterval 重跑函数