gpt4 book ai didi

javascript - 在 contenteditable 中,如何在 Enter 键按下时在 blockquote 之后添加一个段落?

转载 作者:技术小花猫 更新时间:2023-10-29 12:53:27 26 4
gpt4 key购买 nike

我有以下问题。一旦我添加 blockquotecontenteditable , 通过按 Enter 键它移动到一个新行并添加另一个 blockquote元素。它永远持续下去,我无法逃避格式。所需的功能将是无序列表的功能。当您按下 Enter 键时,它会添加一个新的空 <li>元素,但如果您再次按 Enter,它会转义格式,删除之前创建的 <li>并添加一个 <p> .

查看演示:http://jsfiddle.net/wa9pM/

我发现的一个技巧是创建一个空的 <p>blockquote下, 在你创建 blockquote 之前.但是有没有办法用 JavaScript 打破这种格式化行为呢?不知道我会如何检查:如果光标在哪里,它就是行尾,如果它是一个 block 引用并且在 Enter 键按下时,不要添加新的 blockquote .

我正在使用此代码生成 blockquote在 JS 中:

document.execCommand('formatBlock', false, 'blockquote');

最佳答案

在为 iOS 应用程序创建富文本编辑器时,我遇到了同样的问题。每次我插入 <blockquote>在我的文本字段中标记并按 Enter,不可能摆脱 block 引用。

经过一番研究,我找到了一个可行的解决方案。

查找内部 HTML 标签:

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;
}

检查 block 引用标记的出现:

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>

我相信可以轻松调整上面的代码以满足您的需求。如果您需要进一步的帮助,请随时提出。

关于javascript - 在 contenteditable 中,如何在 Enter 键按下时在 blockquote 之后添加一个段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14667764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com