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中的文本内容处于选中状态)方法在三个浏览器中都有效。

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

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

})

发布了21 篇原创文章 · 获赞 3 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_40039641/article/details/82593296