javascript(基于jQuery)实现鼠标获取选中的文字示例【测试可用】

 更新时间:2019年10月26日 10:08:18   作者:那谁家的,小谁  
这篇文章主要介绍了javascript(基于jQuery)实现鼠标获取选中的文字,涉及jQuery响应鼠标事件及页面元素属性动态操作相关实现技巧,需要的朋友可以参考下

本文实例讲述了javascript实现鼠标获取选中的文字。分享给大家供大家参考,具体如下:

HTML部分:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>JS Bin</title>
</head>
<body>
<p>你好啊,那谁家的小谁。听说你在找一个人。我知道她在哪里。</p>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>

1、获取选中的文字:

document.selection.createRange().text; IE9以下使用

window.getSelection().toString(); 其他浏览器使用

$('p').mouseup(function(){
  var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
  alert(txt) ;
})

完整demo示例:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>JS Bin</title>
</head>
<body>
<p>你好啊,那谁家的小谁。听说你在找一个人。我知道她在哪里。</p>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$('p').mouseup(function(){
  var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
  alert(txt) ;
})
</script>
</body>
</html> 

运行效果:

2、取消处于选中状态的文字:

document.selection.empty(); IE9以下使用

window.getSelection().removeAllRanges(); 其他浏览器使用

$('p').mouseup(function(){
  window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
})

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery操作json数据技巧汇总》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》及《jquery选择器用法总结

希望本文所述对大家jQuery程序设计有所帮助。

相关文章

最新评论