上下文:
我试图找出一种方法来判断某个用户高亮显示的文本部分是否包含一个类,如果包含了,则不允许用户突出显示该文本块。
在我的网站上,用户可以创建自己的文章。在这些文章中,用户可以高亮显示文本并对其进行评论。以这篇文章为例:
Lorem ipsum dolor同为圣洁动物
如果这是用户的文章,我可以进去高亮显示文本"Lorem“,如下所示:
"Lorem ipsum dolor -“
这将在突出显示的文本周围创建一个类,该文本将background-color设置为grey。
此时,我不允许用户高亮显示任何已经突出显示的文本("Lorem“),因为我在正确突出显示多个突出显示部分的单词时遇到了问题。
因此,我需要一个系统,当用户突出显示包含已经包含在类中的文本的任何部分时,例如:
"Lorem ipsum dolor do consectetur adipiscing elit do eiusmod“
中的突出显示"ipsum dolor“,包括"ipsum",它已经被高亮显示,并且已经具有一个类名。
然后弹出一个警报,并没有突出显示。
到目前为止我尝试过的:
我已经尝试过使用css属性user-select: none;设置。
directly
问题&示例JSFiddle:
如何判断高亮显示的文本是否包含来自某个类的文本?
下面是一个示例,说明当用户高亮显示另一个类中包含的文本时希望发生的事情:
$("div").click(function() {
checkIfTextisAlreadyHighlighted();
});
function checkIfTextisAlreadyHighlighted() {
var sel = window.getSelection();
if (sel) {
alert("This text contains the class *class name here* and cannot be highlighted.");
}
}.highlighted {
background-color: lightGrey;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class='highlighted'>Selecting this text should make this message appear if text that already contains class is highlighted</span>. More random text.
</div>
发布于 2020-05-09 15:39:48
关于下列执行情况的一些解释:
querySelector).
下面是一个有用的例子:
$("div").mouseup(function() {
checkIfTextisAlreadyHighlighted();
});
function resetSelection() {
window.getSelection().removeAllRanges();
}
function checkIfTextisAlreadyHighlighted() {
const classToSearch = 'highlighted';
const sel = window.getSelection();
const range = sel.getRangeAt(0);
if (range.startContainer === range.endContainer && range.startContainer.parentElement.classList.contains(classToSearch)) {
alert(`This text contains the class ${classToSearch} and cannot be highlighted.`);
resetSelection();
} else {
if (range.cloneContents().querySelector(`.${classToSearch}`) !== null) {
alert(`This text contains the class ${classToSearch} and cannot be highlighted.`);
resetSelection();
}
}
}.highlighted {
background-color: lightGrey;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class='highlighted'>Selecting this text should make this message appear if text that already contains class is highlighted</span>.
More random text.
<span class='highlighted'>Selecting this text should make this message appear if text that already contains class is highlighted</span>.
More random text.
</div>
发布于 2020-05-13 10:22:36
如果您只想避免用户选择特定突出显示的文本,则可以向其类中添加;。
.highlighted {
background-color: grey;
user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
-moz-user-select: none;
}<span class="highlighted">Lorem ipsum</span> dolor sit amet consectetur adipiscing elit sed do eiusmod.
https://stackoverflow.com/questions/61650353
复制相似问题