js获取鼠标选中的文字

时间:2023-03-09 05:50:37
js获取鼠标选中的文字

1、获取选中的文字:

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

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

$('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();
})

上述方法不仅对div或p标签中的文本有效(会自动忽略选中的‘图片’),在ie和chrome中对input中的文本也有效,但在firefox中无效,jquery

的.select()事件(仅对input有效)或js的onselect事件(仅对input有效)和js的.select()(使input中的文本内容处于选中状态)方法在三个浏览器中都有效。

可以用鼠标选中下段文字测试效果:

是他,是他,是他,就是他.我们的朋友小哪吒.是他,就是他,是他,就是他.少年英雄,小哪吒.上天他比~(稍长音),天要高~(同上).下海他比~(同上),海更大啊~啊~(同上).智斗妖魔~,勇降鬼怪.少年英雄,就是小哪吒.有时,他很聪明.有时,他也犯傻.js获取鼠标选中的文字他的个头跟我一般高.有时,他很努力.有时,他也贪玩.他的年级和我一般大~~(长音).上天他比~(稍长音),天要高~(同上).下海他比~(同上),海更大啊~啊~(同上).智斗妖魔~,勇降鬼怪.少年英雄,就是小哪吒~~(长音).

3、使某Dom中的文字处于选中状态:

IE中关于range参见http://msdn.microsoft.com/en-us/library/ie/ms536401%28v=vs.85%29.aspx

$('.somedom').click(function(){
/* not ok for firefox
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();;
selection.addRange(range);*/
this.focus();
if(window.getSelection){
var range=document.createRange();
range.selectNodeContents(this);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range)
}
else if(document.selection){
//for ie
var range=document.body.createTextRange()
range.moveToElementText(this)
range.select();
}