博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Text selection in div(contenteditable) when double click
阅读量:6860 次
发布时间:2019-06-26

本文共 2205 字,大约阅读时间需要 7 分钟。

背景:

     在最近项目中,碰到一个问题:有一个可编辑的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 want13         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 next21         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 way29         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 first55     window.setTimeout(function() {56         selectRange(caretRange);57     }, 0);58   59     return false;60 };

html:

1 
Some editable text. Double click to edit

 

转载于:https://www.cnblogs.com/wuya16/p/3220380.html

你可能感兴趣的文章
长连接
查看>>
MySQL数据库权限操作指南
查看>>
rabbitmq的web管理界面无法使用guest用户登录
查看>>
HBase的集群搭建(1、3、5节点都适用)
查看>>
将复杂form表单序列化serialize-object.js
查看>>
C语言 · 出现次数最多的数
查看>>
正则获取HTML代码中img的src地址
查看>>
Java 根据当前时间获取明天、当前周的周五、当前月的最后一天
查看>>
3.View绘制分析笔记之onLayout
查看>>
linux语言设置i18n(转)
查看>>
双链表插入 删除详解
查看>>
迄今为止计算机视觉领域超有实力的研究人物主页
查看>>
Java中值类型和引用类型的区别
查看>>
php 页面间传递数据
查看>>
[Node.js] Initialize a LoopBack Node.js Project through the CLI
查看>>
nginx补丁格式说明(CVE-2016-4450为例)
查看>>
C#编程(八十一)---------- 捕获异常
查看>>
Kinect2.0点云数据获取
查看>>
Omi新成员omi-router正式发布
查看>>
CentOS7.2 安装Tomcat
查看>>