本文实例讲述了javascript实现鼠标获取选中的文字。分享给大家供大家参考,具体如下:
HTML部分:
JS Bin你好啊,那谁家的小谁。听说你在找一个人。我知道她在哪里。
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示例:
JS Bin你好啊,那谁家的小谁。听说你在找一个人。我知道她在哪里。
$('p').mouseup(function(){
var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
alert(txt) ;
})
运行效果:
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程序设计有所帮助。