说我有一个文本,看起来像这样:
<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>
项目的文本位,然后按一个按钮突出显示或加粗选择。对用户来说,它看起来像这样:
一些狐狸跳过一些围栏的句子。又一句话 其中一只狗跳过一些狐狸。还有一个,我想你 明白了。
我想知道如何保存这样的东西。我通过遍历一个吐出句子的数组来创建这些跨度,但我怎么能记住一个高光跨越两个句子并且一个高亮(我说这是因为我当然可以节省句子2的结尾和句子3的开头都会突出显示,但是这会将亮点视为单独的)?
顺便说一句,我在这里使用React。
答案 0 :(得分:0)
您可以获取用户突出显示的字符,无论这些字符的分配位置如何。
以下是使用普通javascript进行操作的示例:
function selected() {
if (window.getSelection) {
return window.getSelection().toString()
} else if (document.selection) {
return document.selection.createRange().text
}
}
function boldify (txt) {
var ls = txt.split(' ')
$.each($('span'), function (k, v) {
var currentText = $(v).text()
currentText = boldWord(ls, currentText)
$(v).html(currentText)
});
}
function boldWord (ls, text) {
$.each(ls, function (k, v) {
console.log('v', v)
text = text.replace(v, '<b>' + v + '</b>')
});
return text
}
function saveHighlight (txt) {
console.log('Save <' + txt + '>')
}
// this helper var will hold all the span
// the user interacts with (you can pass this to get the el instead
// of className
var interactedSpan = []
// I said plain js, so sorry about the jQuery, just to be faster
$('span').mouseup(function () {
interactedSpan.push(this.className)
var myText = selected()
saveHighlight(myText)
boldify(myText)
console.log('interactedSpan:', interactedSpan)
});
$('span').mousedown(function () {
interactedSpan.push(this.className)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="a"> Some sentence in which a fox jumps over some fence. </span>
<span class="b"> Another sentence in which a dog jumps over some fox. </span>
<span class="c"> Yet another one, I think you get the idea. </span>
不确定我为什么被投票,无论如何使用interactedSpan
改进了答案,现在还添加了粗体版本,他要求保存或加粗
答案 1 :(得分:0)
您可以只使用两个单独的粗体标记,以便您可以使用有效的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>
或者你可以避免将每个句子保持在不添加任何值的范围内。而是将开始和结束标记保持在数组中的句子中,然后将它们连接起来并显示为单个段落。开始和结束标记不必是<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);