zoukankan      html  css  js  c++  java
  • 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中的文字处于选中状态:

    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();
        }     
  • 相关阅读:
    数据导入
    数据库导入导出命令
    题库
    struts2的配置文件简洁
    修改oralce11g 字符集为ZHS16GBK
    Linux上安装JDK+Tomcat
    Android中adb的使用
    【转】Android获取IP的方法,并可以判断手机是否联网
    Android中R.java没有自动生成问题
    Android中SQLiteOpenHelper的理解
  • 原文地址:https://www.cnblogs.com/yigeqi/p/3988705.html
Copyright © 2011-2022 走看看