• Text selection in div(contenteditable) when double click


    背景:

         在最近项目中,碰到一个问题:有一个可编辑的div需要双击时可编辑,blur或者回车时将编辑结果保存。你可能注意到双击时,文字会被选中,可编辑区域不会focus到光标位置。考虑到兼容性问题,写了如下代码。做个备份,以备不时之需。

    js:

     1 function getMouseEventCaretRange(evt) {
     2     
     3     var range, x = evt.clientX, y = evt.clientY;
     4     
     5         // Try the simple IE way first
     6         if (document.body.createTextRange) {
     7             range = document.body.createTextRange();
     8             range.moveToPoint(x, y);
     9         }
    10     
    11     else if (typeof document.createRange != "undefined") {
    12         // Try Mozilla's rangeOffset and rangeParent properties, which are exactly what we want
    13         
    14         if (typeof evt.rangeParent != "undefined") {
    15             range = document.createRange();
    16             range.setStart(evt.rangeParent, evt.rangeOffset);
    17             range.collapse(true);
    18         }
    19     
    20         // Try the standards-based way next
    21         else if (document.caretPositionFromPoint) {
    22             var pos = document.caretPositionFromPoint(x, y);
    23             range = document.createRange();
    24             range.setStart(pos.offsetNode, pos.offset);
    25             range.collapse(true);
    26         }
    27     
    28         // Next, the WebKit way
    29         else if (document.caretRangeFromPoint) {
    30             range = document.caretRangeFromPoint(x, y);
    31         }
    32     }
    33     
    34     return range;
    35 }
    36 
    37 function selectRange(range) {
    38     if (range) {
    39         if (typeof range.select != "undefined") {
    40             range.select();
    41         } else if (typeof window.getSelection != "undefined") {
    42             var sel = window.getSelection();
    43             sel.removeAllRanges();
    44             sel.addRange(range);
    45         }
    46     }
    47 }
    48 
    49 document.getElementById("editor").ondblclick = function(evt) {
    50     evt = evt || window.event;
    51     this.contentEditable = true;
    52     this.focus();
    53         var caretRange = getMouseEventCaretRange(evt);
    54       // Set a timer to allow the selection to happen and the dust settle first
    55     window.setTimeout(function() {
    56         selectRange(caretRange);
    57     }, 0);
    58   
    59     return false;
    60 };

    html:

    1 <div id="editor" contenteditable="false">Some editable text. Double click to edit</div>
  • 相关阅读:
    微软忘记修复Mac Office2004/2008安全漏洞 狼人:
    资深黑客谈:安全趋势正在向应用层发展 狼人:
    Web应用防火墙之前世今生 狼人:
    RSA技术总监Bill Duane:安全正因云而改变 狼人:
    微软11月将发布3个补丁 修复11处漏洞 狼人:
    选择透明在按钮上添加图片
    企业组织不管你学的是什么专业,你都应该多少懂些管理学的东西
    最大数组连续子向量的最大和
    异步请求再探异步 ASP.NET 页
    谷歌平台谷歌将推安卓游戏中心 整合社交挖角iOS
  • 原文地址:https://www.cnblogs.com/wuya16/p/3220380.html
Copyright © 2020-2023  润新知