使Tab键在contentEditable div中插入一个制表符,并且不会模糊 [英] Make the Tab key Insert a tab character in a contentEditable div and not blur
问题描述
我通过在div上设置 contentEditable = true
来构建一个简单的文本编辑器(无论如何,我认为textarea的行为方式相同),并且
I'm building a simple text editor by setting contentEditable=true
on a div (anyway i think that textarea behaves in the same way) and i have some problems with the tab key.
我想要的是,当用户按下Tab键时,焦点仍停留在div上,并且将制表符添加到了文本中。
What i want is that when the user presses the tab key, the focus remain on the div and a tab character is added to the text.
我通过在keydown上的事件对象上调用 preventDefault()
解决了问题的第一部分,现在div不会失去焦点,但是我不知道为什么我不能插入字符。
I've solved the first part of the problem by calling preventDefault()
on the event object on keydown and now the div doesn't lose the focus, but i don't know why i can't insert the character.
制表符char的实体代码为	
,但是如果我尝试将此字符串添加到innerHTML Firefox用一个简单的空格代替(不是& nbsp;
只是一个空白)。我也尝试过 \t
,但是结果是一样的。
The entity code for the tab char is 	
but if i try to add this string to the innerHTML Firefox replace it with a simple space (not
just a white space). I also tried with \t
but the result is the same.
所以我的问题是,我怎么在文本中插入制表符?
So my question is, how can I insert a tab character in the text?
推荐答案
之所以只看到一个简单的空格,是因为空格字符序列(除(不间断空格)在div中被视为单个空格字符。如果希望制表符以您期望的方式显示,则需要将其放入< pre>
元素之类的元素中,该元素将空格显示为空白。源HTML,或在带有空格的元素内:pre
通过CSS设置。
The reason why you only see a simple space is because sequences of whitespace characters (except non-breaking spaces) are treated as a single space character inside divs. If you want the tab character to display in the way you expect you'll need to put it inside something like a <pre>
element that renders whitespace as it is in the source HTML, or inside an element with white-space: pre
set via CSS.
这篇关于使Tab键在contentEditable div中插入一个制表符,并且不会模糊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!