Javascript 如何在第一个contenteditable中创建元素
基本上,我需要在第一个contentEditable div中创建一个段落元素Javascript 如何在第一个contenteditable中创建元素,javascript,jquery,html,css,contenteditable,Javascript,Jquery,Html,Css,Contenteditable,基本上,我需要在第一个contentEditable div中创建一个段落元素 <div id="contentEdit" contenteditable="true"> <p> <figure id="figure" contenteditable="false"> <figcaption class="_picCaption" contentEditable="true">
<div id="contentEdit" contenteditable="true">
<p>
<figure id="figure" contenteditable="false">
<figcaption class="_picCaption" contentEditable="true">
image caption
</figcaption>
</figure>
</p>
</div>
发生了什么,我正在标题中创建p元素。
我不知道如何获得figcaption的祖父母的范围。您实际上不必使用范围,只需将contentEdit中的所有元素用p元素包装即可 使用纯JS,您应该将contentEdit中的所有元素移动到新的p元素,然后将其放回contentEdit:
首先正确地编写代码我想如果你想得到任何积极的回应,你可能需要清理上面的代码格式。你能更清楚地解释一下你想要什么吗?
$(document).on("keydown", "#contentEdit", function(e) {
e.stopPropagation();
var element = cp_getSelectionBoundaryElement(true);
if ((e.which || e.keyCode) == 13) {
if (element.tagName == "FIGCAPTION") {
e.preventDefault();
// get the selection range (or cursor position)
var range = window.getSelection().getRangeAt(0);
// create a p
var newElement = document.createElement('p');
newElement.className = '_graf_p';
// if the range is in #contentEdit
if (range.startContainer.parentNode.className === '_picCaption') {
// delete whatever is on the range
range.deleteContents();
// place your p
range.insertNode(newElement);
}
}
}
});
var content = document.getElementById('contentEdit');
var newElement = document.createElement('p');
while (content.firstChild) {
newElement.appendChild(content.firstChild);
}
content.appendChild(newElement);