[英]How to highlight specific words in a text using HTML and Javascript?
[英]how to highlight text and label it on runtime using javascript and html
下面是我的代码。 我想在mouseup
上突出显示文本。 我是Web的新手。 我不知道为什么我的代码无法正常工作。 它没有突出显示任何文本。
有人可以帮助我找到问题吗? 我编写的代码大部分是我从网上到那里复制的内容。
问题2:文本突出显示后,我想用鼠标右键单击打开菜单,其中包含4至5个选项,然后选择其中之一以标记突出显示的文本。 稍后以JSON
格式下载带标签的数据。
首先,我想解决我的第一个问题。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <title>TEST</title> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <style> .red { color: red; } ; </style> <script> thisRespondHightlightText(".select--highlight--active"); function thisRespondHightlightText(thisDiv) { $(thisDiv).on("mouseup", function() { var selectedText = getSelectionText(); var selectedTextRegExp = new RegExp(selectedText, "g"); var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>"); $(this).html(text); }); } function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } </script> </head> <body> <div class="select--highlight--active">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div> </body> </html>
更改此设置,jQuery首先需要准备
$(function() {
thisRespondHightlightText(".select--highlight--active");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.