开发者

Allow Tabbing in a contentEditable div with execCommand

开发者 https://www.devze.com 2023-04-11 12:06 出处:网络
I 开发者_运维百科am making an application where I need for a contentEditable div to be allowed to have tabs in it. I have already figured out that it is really not possible to have to work correctly.

I 开发者_运维百科am making an application where I need for a contentEditable div to be allowed to have tabs in it. I have already figured out that it is really not possible to have to work correctly. So is there a way that on keyDown it adds the HTML code for a tab, which is

	

What I have so far is this

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
    }
}

If anybody knows if there is a way to do this, or if that is the way and I am simply doing it wrong, please tell me! Thanks!


The HTML spec specifies that a TAB char should be treated as a single white space except for when it's contained inside a <pre> element.

The code that you posted above does work and it does insert a TAB char but it's just displayed by the browser as a white space. If you can put your entire editable content in a <pre> tag then your tabs will show up.

If you only want to use the tabs to indent content, you can also look into

execCommand('indent', false, null)


For future readers, perhaps a simpler solution is to just use the 'pre' white-space style. original post here.

white-space: pre;


"indent" command, firefox wraps the selected text with blockquote element.
So one can define a margin-left or padding-left property for blockquote element to represent tabbing.
The "outdent" command will remove the blockquote element and hence the styles.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号