【发布时间】:2021-02-27 07:55:34
【问题描述】:
我是 HTML/JS 的新手,我正在尝试将文本编辑器作为一个小项目。 如果我没有清楚地解释我的想法,请原谅我。
假设我的 contenteditable div 环境中有以下文本,并让 | 代表光标(就像在大多数编辑器中一样):
hi this is some text
here is some mor|e text
hello, world!
我怎样才能返回文本“这里还有一些文本”?
我正在使用 jQuery,我想我想使用 onClick 处理程序,但这不会响应用于导航的箭头键。我需要什么样的事件处理程序?到目前为止,我已经解析了文本以替换 div 分隔符,但我对如何继续有点迷茫。
你会建议做什么? (一般链接/建议也可以,我正在尝试通过这个项目了解更多信息)
编辑,这是我的 html:
<div id="editor" class="editor" contenteditable="true"></div>
这是 JS:
$(document).on('keydown', '.editor', function(e){
//detect 'tab' key
if(e.keyCode == 9){
//add tab
document.execCommand('insertHTML', false, '	');
//prevent focusing on next element
e.preventDefault()
}
var text = $("#editor").html();
console.log("MYLITERAL:" + text);
// parse the string :)
// for the div tags, replacing them with \n
var tmp = text.replace(/<div>/g, "");
tmp = tmp.replace(/<\/div>/g, "");
tmp = tmp.replace(/<br>/g, "\n");
console.log(tmp);
document.getElementById("demo").innerHTML = tmp;
});
【问题讨论】:
-
你应该显示你的 html.code。
-
在 SO 上似乎有很多相关的问题,所以我建议尝试更努力地搜索 :-) 一些示例:stackoverflow.com/questions/7745867/…、stackoverflow.com/questions/12553025/…、stackoverflow.com/questions/9185630/…、stackoverflow.com/questions/3153995/…
-
@Frenchy 做到了!
标签: javascript html jquery css