contenteditable =“true”:创建语法高亮显示的输入表单 [英] contenteditable="true": creating a syntax highlighted input form
问题描述
我现在摆弄contenteditable =true来创建一个语法高亮的输入框。我正在写一个jquery插件,它将< input>
标签转换为< div contenteditable =true>
容器。详细地说,它隐藏< input>
,并在它后面插入< div>
容器。
在我的小提琴中,高亮功能只是一个简单的替换功能,用于高亮显示容器中的所有'AND'。这是我的小提琴:
http://jsfiddle.net / 3Rhz8 / 2 /
如果容器的内容发生变化,插件必须
- 将内容与输入内容同步
- 更新语法突出显示
在我的例子中,我只是在听基调事件。现在,当我想更新容器的语法高亮显示时出现问题。当通过 .html()
或容器的 innerHTML
属性更改输入时,游标状态将重置。有没有办法来防止这种情况,或者我可以保存/恢复光标位置?
有一个完美的API保存并恢复光标位置:
http://code.google.com/p/rangy/
这是一个简洁的API。
所有你需要做的是
var savedSel = rangy.saveSelection();
保存光标位置,然后
rangy.restoreSelection(savedSel);
恢复光标位置。您可以在这里阅读更多相关信息: http://code.google.com/p/rangy / wiki / SelectionSaveRestoreModule
I'm currently fiddling around with contenteditable="true" to create a syntax highlighted input box. I'm writing a jquery plugin that converts a <input>
tag to a <div contenteditable="true">
container. In detail, it hides the <input>
and inserts the <div>
container after it.
In my fiddle, the highlight function is just a simple replace function to highlight all 'AND's in the container. Here's my fiddle:
If the content of the container is changed, the plugin has to
- sync the content with the content of the input
- update the syntax highlighting
In my example, I'm just listening to the keyup event. Now, there's a problem when I want to update the syntax highlighting of the container. When the input is changed via .html()
or the container's innerHTML
property, the cursor state resets. Is there a way to prevent this, or can I save/restore the cursor position ?
There is a perfect API for saving and restoring the cursor position: http://code.google.com/p/rangy/
It's the rangy API. All you have to do is
var savedSel = rangy.saveSelection();
to save the cursor position and then
rangy.restoreSelection(savedSel);
to restore the cursor position. You can read more about this here: http://code.google.com/p/rangy/wiki/SelectionSaveRestoreModule
这篇关于contenteditable =“true”:创建语法高亮显示的输入表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!