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>

 

你可能感兴趣的:(contenteditable)