I've got a rich text editor in an iframe with designMode that does syntax highlighting for small blocks of text. I'd like it to update the highlighting on keyup, but messing with the DOM causes the frame to blur, thus every time you push a key the caret disappears and you can't type anymore. That wouldn't be a problem if the parser could remember where the caret is, and then refocus the iframe开发者_如何学Python and replace the caret. I've read up on getSelection()
and its relatives, but apparently onkeyup removes the selection, at least in Chrome - calling getSelection()
inside an onkeyup always yields a null selection. Is there a way around this?
This is what I have:
<iframe>
<html>
<head>
<script>
function parse() {
if(window.getSelection().type != 'None') {
var range = window.getSelection().getRangeAt(0);
}
var text = document.body.textContent;
//Parse text, output is stored in newtext
document.body.innerHTML = newtext;
document.body.focus();
if(range) {
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
</script>
</head>
<body onload="document.designMode = 'on'; document.onkeyup = parse;">
Text entered appears here
</body>
</html>
</iframe>
I would recommend to use some other code highlighter. Like CodeMirror for example.
not sure if you're open to using a JS framework, but mootools has some pretty nifty selection utilities (e.g., http://mootools.net/docs/more/Element/Element.Forms#Element:getCaretPosition)
精彩评论