javascript - How to prevent accidental deletion of contenteditable ul in IE10? -
i want have contenteditable ul on page. however, in internet explorer 10, if click it, select either right click menu or ctrl+a, delete, ul element gets deleted off page.
what best way prevent this, or @ least detect when happens , insert replacement ul?
i'd suggest intercepting delete , backspace keys , doing delete manually. steps are:
- get selected range
- adjust ends of range lie within editable
<ul>
element if outside - call
deletecontents()
on range.
note following won't work on ie <= 8. if need support browsers, use rangy library, used simplify deleteselectedcontent()
slightly.
demo: http://jsfiddle.net/timdown/stcxa/3/
code:
var editor = document.getelementbyid("editor"); function deleteselectedcontent() { if (window.getselection) { var sel = window.getselection(); if (sel.rangecount > 0) { var range = sel.getrangeat(0); var editorrange = range.clonerange(); editorrange.selectnodecontents(editor); // adjust selection range boundaries if (range.compareboundarypoints(range.start_to_start, editorrange) == -1) { range.setstart(editorrange.startcontainer, editorrange.startoffset); } if (range.compareboundarypoints(range.end_to_end, editorrange) == 1) { range.setend(editorrange.endcontainer, editorrange.endoffset); } range.deletecontents(); } } } editor.addeventlistener("keydown", function(evt) { if (window.getselection && !window.getselection().iscollapsed && (evt.keycode == 8 || evt.keycode == 46)) { evt.preventdefault(); deleteselectedcontent(); } }, false);
Comments
Post a Comment