如何克服多项选择问题

温尼

我在中有一个示例段落文本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);
});
span {
  color: green;
}
<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>

陈范Chan

简而言之,您只需在范围内添加一个或多个事件触发器即可控制选择方式。您没有指定如果选择在范围内结束时会发生什么,但是我相信您可以弄清楚该部分。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章