允许使用execCommand在contentEditable div中进行Tabbing

com*_*omu 6 html javascript jquery dom contenteditable

我正在创建一个应用程序,我需要一个contentEditable div允许其中有选项卡.我已经发现,实际上不可能正常工作.那么有没有办法在keyDown上添加标签的HTML代码,即

	
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有这个

document.getElementById('codeline').contentEditable='true';
document.getElementById('codeline').onkeydown=function(e){
    if(e.keyCode==9){
        e.preventDefault();
        //document.getElementById('codeline').contentWindow.document.execCommand("InsertHTML",false,"	"); 
        //Thought this would work but it doesn't
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人知道是否有办法做到这一点,或者如果那样,我只是做错了,请告诉我!谢谢!

dcr*_*cro 3

HTML 规范指定 TAB 字符应被视为单个空格,除非它包含在<pre>元素内。

您上面发布的代码确实有效,并且确实插入了一个 TAB 字符,但浏览器只是将其显示为空格。如果您可以将整个可编辑内容放在<pre>标记中,那么您的选项卡就会显示。

如果您只想使用制表符来缩进内容,您也可以查看

execCommand('indent', false, null)