我有一个示例段落文本p tag.如果我在段落中选择一些文字.我正在将其文本颜色从黑色更改为绿色并将其包装为span tag添加为其选择的类.但我可以选择已经选择的文本.我不希望再次选择所选文本.
我在链接中给出了示例代码:http://jsfiddle.net/2w35p/81/
function getSelectedText() {
t = (document.all) ? document.selection.createRange().text : document.getSelection();
return t;
}
$('body').mouseup(function() {
var selection = getSelectedText();
var selection_text = selection.toString();
var span = document.createElement('SPAN');
span.textContent = selection_text;
span.className = "selectedText"
var range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(span);
});Run Code Online (Sandbox Code Playgroud)
span {
color: green;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged..
<p>Run Code Online (Sandbox Code Playgroud)
简而言之,您只需在范围内添加一个或多个事件触发器即可控制如何进行选择。您没有指定如果选择在范围内结束会发生什么,但我相信您可以弄清楚该部分。
var span = document.createElement('SPAN');
span.textContent = selection_text;
span.className = "selectedText";
span.onselectstart = ()=> !!window.getSelection().empty(); //new
span.onmouseover = ()=> !!window.getSelection().empty(); //new
if (selection_text) { //new
var range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(span);
} //new
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |