Allow Tabbing on contentEditable with execCommand

I am creating an application in which I need to allow tabs in the contentEditable div. I already realized that it is really impossible to work correctly. So there is a way that on keyDown adds HTML code for the tab, which

	 

What I still have is

 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 anyone knows if there is a way to do this, or if that is the case, and I'm just doing it wrong, please tell me! Thanks!

+6
source share
3 answers

The HTML specification indicates that a TAB char should be treated as a single empty space, unless it is contained within a <pre> element.

The code you posted above works and it inserts a TAB char, but it just displays as a space in the browser. If you can put all editable content in the <pre> tag , your tabs will appear.

If you want to use tabs for indentation content, you can also view

execCommand('indent', false, null)

+3
source

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

 white-space: pre; 
+3
source

"indent", firefox wraps the selected text with a blockquote element.
Thus, for the blockquote element for the tabbing view, you can define the margin-left or padding-left property.
The outdent command will remove the blockquote element and therefore the styles.

0
source

Source: https://habr.com/ru/post/898895/


All Articles