如何强制< br> Firefox ContentEditable中的换行符 [英] How to force <br> line break in Firefox ContentEditable

查看:314
本文介绍了如何强制< br> Firefox ContentEditable中的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在网站上运行的JavaScript所见即所得编辑器(与CKEditor不同)。

当您按下 Enter时,IE会创建< br> / b>

这很好,但不幸的是,Firefox(我已经测试过5和7)仍然会生成< ; p> 元素,并且只有在使用 Shift + Enter 时,才会生成< br>

有没有办法让Firefox在contentEditable中始终生成<

解决方案

从标准看,这个行动看起来应该是被处理的。当在回车键上没有设置修饰符时块被打破,并且当按下移位时使用< br> 的s。 [来源]。



也就是说,这并不能解决你的问题,所以让我们来解决这个问题。这行应该做

$ p code> document.execCommand('insertBrOnReturn',false,true);

设置它以便当您返回时,它只会放入一个 < br> 标签。这是只支持FF ,所以它不应该影响IE上的任何东西。不过,不知道其他浏览器。



注意:如果用户第二次点击 Enter 输入任何内容,无论如何都会创建一个新的段落标记。为了防止这种情况发生,您可以使用按键事件捕捉 Enter 并停止它,或者您可以插入& (b $ p

$ p
$ b $ p $)在这个笔记中, keypress 元素的状态。懒惰的解决方案(和我会建议,除非它是重要的不这样做)是插入在每个 Enter 键之前。如果你想这样做,我会检查元素的 .innerHTML ,看看最后几个字符(不修剪内容)是不是< br /> (所以也许正则表达式匹配 / \< br \??\ /?\> $ / code>)。


I have a JavaScript WYSIWYG editor (not unlike CKEditor) running on a site.

It has a setting that makes IE create <br> line breaks when you press Enter in the editor.

That works great, but unfortunately, Firefox (I've tested with 5 and 7) will still generate <p> elements, and generate <br> s only if you use Shift + Enter.

Is there a way to make Firefox always generate <br> elements in a contentEditable?

解决方案

From looking at the standards, it looks like this action is the way it is supposed to be handled. Blocks are broken when no modifier is set on an enter key, and <br>'s are used when shift is pressed. [Source].

That said, that does not solve your problem, so let's work on that. This line should do

document.execCommand('insertBrOnReturn', false, true);

Set's it so that when you just hit return, it only puts in a <br> tag. This is only supported by FF, so it shouldn't affect anything on IE. Don't know about other browsers though.

Note: If the user hits Enter a second time, without typing anything, it creates a new paragraph tag no matter what. To prevent this, you can catch the Enter using the keypress event and stop it, or you could insert in a &nbsp; before you continue with the event (what I'd recommend).

The tough part for you with this note is checking on the state of the element on keypress. The lazy solution (and the one I would recommend unless it's important to not do this) is to just insert it before every Enter key. If you want to do it the other way, I would check the .innerHTML for the element and see if the last few characters (without trimming the content) are <br/> (so maybe a regex match on /\<br\s?\/?\>$/).

这篇关于如何强制&lt; br&gt; Firefox ContentEditable中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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