0

我有一个mouseUp监听 div 的事件,以便在用户选择文本时进行通知。我得到选定的文本,window.getSelectoin().toString()但我也想通过提供字体颜色来标记该特定文本,但不知道如何。我无法向该特定选择范围添加跨度。知道如何实现这一目标吗?可以说我有 div 如下

<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum
</div>

因此,如果用户在其中选择了一些文本,我应该用一些字体颜色对其进行标记。字体颜色应永久粘贴文本。所以我不能使用::Selection。提前致谢

4

3 回答 3

1

我认为您需要的是 CSS 而不是任何 JS 脚本:

您可以::selection为此使用属性:


您可以运行以下代码段(代码参考和更多),希望这会对您有所帮助

.example-color::selection {
  color: #8e44ad;
}
.example-background-color::selection {
  background-color: #f1c40f;
}
.example-background::selection {
  background: #e74c3c;
}
.example-both::selection {
  background-color: #8e44ad;
  color: white;
}
.example-shadow::selection {
  text-shadow: 1px 1px 0 #27ae60;
}
.example-input::selection {
  background: #2ecc71;
}
.example-textarea::selection {
  background: #34495e;
  color: white;
}
body {
  font-family: 'Source Sans Pro', Arial, sans-serif;
  line-height: 1.45;
  background: #E0DCCC;
  color: #333;
  padding: 1em;
  font-size: 18px;
}

p,input,textarea  {
  margin-bottom: 1em;
}
input,textarea {
  display: block;
  font-size: 1em;
  font-family: inherit;
}
<p>Select me to see normal behavior.</p>
<p class='example-color'>Try selecting me for a different text color.</p>
<p class='example-background-color'>You can select me for a different background color.</p>
<p class='example-background'>You can also select me for a different background.</p>
<p class='example-both'>Guess what&hellip; you can select me for a different background color and text color.</p>
<p class='example-shadow'>How about a text-shadow? Sure, select me for a different text-shadow.</p>
<p class='example-background-color'>
  What about nest elements? Select me for a different background color.
  <span class='example-color'>And this sentence is just a color selection.</span>
  Nesting works!
</p>
<input class='example-input' type='text' value='Inputs work!*'>
<textarea class='example-textarea' cols='30' name='' rows='10'>Textarea, too!*</textarea>
<div class='foot-notes'>*not Safari</div>

于 2020-05-20T04:04:10.427 回答
0

你可以借助 CSS,如果 CSS 可以处理一些事情,就不要去 JS。在您的样式表中添加此样式

::selection {
    color: red;
    background: yellow;
 }
于 2020-05-20T04:13:49.083 回答
0

最后,经过一天的谷歌搜索,我能够实现这一目标。万一将来有人需要这个:P 我所做的是 - 使用 contentEditable 使包装器 div 为 true 并使用 document.execCommand api 进行所需的定制。注意:但是我不会让用户在下面的处理程序中使用 preventDefault 编辑内容

        onCut={(e)=>e.preventDefault()}
        onPaste={(e)=>e.preventDefault()}
        onKeyPress={(e)=>e.preventDefault()}
        onKeyDown={(e)=>e.preventDefault()}``` Thanks for helping
于 2020-05-20T12:09:28.513 回答