问题描述
我有以下问题。一旦我在 contenteditable
中添加一个 blockquote
,按下Enter键将移动到一个新行并添加另一个 blockquote
元素。它永远持续下去,我无法逃避格式化。所需的功能将是无序列表的功能。当你按下回车键时,它会添加一个新的空< li>
元素,但是如果再次按下Enter键,它会转义格式,删除以前创建的< li>
并添加< p>
。
I have the following problem. Once I add a blockquote
in contenteditable
, by pressing Enter key it moves to a new line and adds another blockquote
element. It goes on forever, and I can’t escape the formatting. The desired functionality would be that of the unordered list. When you press the Enter key it adds a new empty <li>
element, but if you press Enter again, it escapes the formatting, removes the previously created <li>
and adds a <p>
.
退出演示:
我发现的一个窍门是在你之前在 blockquote
下创建一个空的< p>
创建一个 blockquote
。但是有没有办法用JavaScript打破这种格式化行为?不知道我该如何检查:如果光标位于哪里,这是行的末尾,如果它是一个blockquote并按Enter键,请不要添加新的 blockquote
。
One hack I found was to create an empty <p>
under the blockquote
, before you create a blockquote
. But is there a way to break this formatting behaviour with JavaScript? No idea how I would check: if where the cursor is, it’s the end of the line and if it’s a blockquote and on Enter key press, don’t add a new blockquote
.
我使用此代码在JS中生成 blockquote
:
I’m using this code to generate a blockquote
in JS:
document.execCommand('formatBlock', false, 'blockquote');
推荐答案
在为iOS应用程序创建富文本编辑器时面临同样的问题。每当我在我的文本字段中插入一个< blockquote>
标签并按下,就不可能摆脱block-引用。
While creating a rich text editor for an iOS application i faced the same problem. Every time i've inserted a <blockquote>
tag in my text field and pressed , it was impossible to get rid off the block-quote.
经过研究,我找到了一个可行的解决方案。
After researching a bit, i've found a working solution.
查找内部HTML标签:
Finding inner HTML tags:
function whichTag(tagName){
var sel, containerNode;
var tagFound = false;
tagName = tagName.toUpperCase();
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
containerNode = sel.getRangeAt(0).commonAncestorContainer;
}
}else if( (sel = document.selection) && sel.type != "Control" ) {
containerNode = sel.createRange().parentElement();
}
while (containerNode) {
if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {
tagFound = true;
containerNode = null;
}else{
containerNode = containerNode.parentNode;
}
}
return tagFound;
}
检查块引用标记的出现次数:
function checkBlockquote(){
var input = document.getElementById('text_field_id');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 13){
if (whichTag("blockquote")){
document.execCommand('InsertParagraph');
document.execCommand('Outdent');
}
}
};
}
触发按键事件:
<body onLoad="checkBlockquote();">
<!-- stuff... -->
</body>
我相信上面的代码可以根据您的需要轻松调整。如果您需要进一步帮助,请随时询问。
I believe the code above can be adjusted to fit your needs easily. If you need further help, feel free to ask.
这篇关于在contenteditable中,如何在输入按键上的blockquote后添加段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!