【问题标题】:How can I keep the text highlighted with JS?如何让 JS 突出显示文本?
【发布时间】:2021-11-12 07:37:11
【问题描述】:

我正在做一个概念项目。选择时突出显示文本。

一旦选中,我必须保持文本突出显示。

<div class="reveal" id="textToSelect"> 
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
    <span class="reveal-text">Ctexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
</div>

我使用 execommand 在选择时创建了一些带有背景颜色的跨度。它可以工作,但 execommand 现在已过时。

document.getElementById('textToSelect').addEventListener('mouseup', function() {
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
  range = sel.getRangeAt(0);
}

document.designMode = "on";
if (range) {
  sel.removeAllRanges();
  sel.addRange(range);
}

document.execCommand("hiliteColor", false, "red");

document.designMode = "off";
});

如何在没有 execCommand 的情况下创建这些跨度?我看到了答案,但对于这种特定情况来说可能太笼统了。

非常感谢您的支持!

【问题讨论】:

  • 选择的意思是“点击”还是“鼠标上移”?
  • 理想情况下,我想在范围的每一侧创建带有背景颜色的标签来模拟突出显示。
  • 范围是多少?我没看懂那句话里的问题。当您将鼠标悬停在#textToSelect 上时,您需要突出显示内容文本吗?是吗?>

标签: javascript html css frontend highlight


【解决方案1】:

鼠标悬停在#textToSelect 上时是否会出现以下预期行为?

#textToSelect .reveal-text {
  background-color: #ddd;
  cursor: pointer;
}

#textToSelect:hover .reveal-text {
  background-color: yellow;
}
<div class="reveal" id="textToSelect"> 
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
    <span class="reveal-text">Ctexttexttexttexttexttexttexttexttext</span>
    <span class="reveal-text">texttexttexttexttexttexttexttext</span>
</div>

【讨论】:

  • 并非如此。我想根据选择在 .reveal-text 内创建其他跨度。例如,如果我有这个:Bonjour Monsieur comment allez-vous ? 然后我强调“先生评论”。所以 DOM 会变成这样: Bonjour Monsieur comment allez-vous ?
【解决方案2】:

如果您需要在单击后更改颜色,则需要将其添加到您的显示文本类中,因此在您的 css 文件中添加:

a:active {
  color: red;
}

相应地改变颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2015-11-26
    • 2022-06-16
    相关资源
    最近更新 更多