如何制作tab键在contentEditable div中插入制表符? [英] How to make the tab key Insert a tab character in a contentEditable div?

查看:371
本文介绍了如何制作tab键在contentEditable div中插入制表符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过在div上设置 contentEditable = true 来构建一个简单的文本编辑器(无论如何,我认为textarea的行为方式相同),并且我遇到了一些问题



我想要的是,当用户按下Tab键时,焦点会保留在div上,并且将制表符添加到文本中。



我已经通过在keydown事件对象上调用 preventDefault()来解决问题的第一部分,现在div不会失去焦点,但我不知道为什么我不能插入角色。



tab字符的实体代码是	 但是如果我尝试将此字符串添加到innerHTML Firefox将其替换为一个简单的空间(而不是& nbsp; 只是一个空格)。我也试过用 \t 但结果是一样的。

所以我的问题是,我怎么能在文本中插入一个制表符?

解决方案

你只看到一个简单空格的原因是因为空白字符序列非破坏空间)被视为divs中的单个空格字符。如果您希望制表符按您期望的方式显示,您需要将它放在类似于< pre> 元素的元素中,该元素呈现空白,因为它在源HTML。


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.

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.

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.

The entity code for the tab char is &#09; but if i try to add this string to the innerHTML Firefox replace it with a simple space (not &nbsp; 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?

解决方案

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.

这篇关于如何制作tab键在contentEditable div中插入制表符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆