使用JavaScript清除文本选择 [英] Clear Text Selection with JavaScript

查看:121
本文介绍了使用JavaScript清除文本选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到答案的简单问题:如何使用JavaScript(或jQuery)取消选择可在网页上选择的任何文本?例如。用户点击和拖动以突出显示一些文本 - 我希望有一个deselectAll()函数清除此选择。我应该怎么写呢?

Simple question which I can't find the answer to: how can I use JavaScript (or jQuery) to deselect any text which may be selected on a webpage? E.G. user clicks and drags to highlight a bit of text -- I want to have a function deselectAll() which clears this selection. How should I go about writing it?

感谢您的帮助。

推荐答案

if (window.getSelection) {
  if (window.getSelection().empty) {  // Chrome
    window.getSelection().empty();
  } else if (window.getSelection().removeAllRanges) {  // Firefox
    window.getSelection().removeAllRanges();
  }
} else if (document.selection) {  // IE?
  document.selection.empty();
}

归功于Y先生。

这篇关于使用JavaScript清除文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆