问题
I am using popular Rangy library inside contenteditable DIV. My code is pretty simple:
var saved_selection = false;
$('#contenteditable').bind('keypress mouseup', function(e){
$(this).find('.rangySelectionBoundary').remove();
saved_selection = rangy.saveSelection();
});
Now this works pretty good in Chrome and FF. However, in Opera it behaves very strangely, because it doesn't allow to insert any characters in contenteditable and it rather looses focus, or at least it seems so.
I have prepared jsFiddle for testing. In Opera, it's not possible to enter any chars in editable DIV: http://jsfiddle.net/twST6/1/
Anybody can explain and solve my problem how to make this code work in Opera ?
Thanks in advance for any help.
回答1:
Interesting. I assume that the problem is that changing the DOM during a keypress event in Opera stops the native browser keypress action from occurring (which I think I've seen before). I don't see an easy way round it apart from avoiding saving the selection on every keypress. Another solution is to save the selection as character indices within the content, which doesn't change the DOM and should therefore work. See this answer:
https://stackoverflow.com/a/5596688/96100
I'm also close to releasing a more robust character index-based selection save/restore for Rangy. See demo here:
http://rangy.googlecode.com/svn/trunk/demos/textrange.html
Incidentally, there is built-in method for removing the selection markers in Rangy:
rangy.removeMarkers(saved_selection);
来源:https://stackoverflow.com/questions/10672881/why-rangy-library-doesnt-work-with-contenteditable-in-opera