我正在尝试使用按钮单击和java脚本功能在光标点的内容框中添加内容,它在框内添加,但是如果我单击外部某处并再次单击按钮,它会在按钮内添加内容。如何限制该功能仅在内容 div 中添加内容。以下是 HTML 和 CSS:
var heading = '<span style="color:#0091DA; margin-bottom:30px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; font-size:14px; line-height:120%;">Subheadings in Arial Bold 10.5pt (14px) light blue</span>';
function pasteHtmlAtCaret(html, selectPastedContent) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// only relatively recently standardized and is not supported in
// some browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(),
node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
var firstNode = frag.firstChild;
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
if (selectPastedContent) {
range.setStartBefore(firstNode);
} else {
range.collapse(true);
}
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if ((sel = document.selection) && sel.type != "Control") {
// IE < 9
var originalRange = sel.createRange();
originalRange.collapse(true);
if (document.getElementById('edit-content')[0].getAttribute("contenteditable", "true")) {
sel.createRange().pasteHTML(html);
}
}
}
.main {
border: 1px solid #000;
width: 500px;
height: 500px;
}
.content {
border: 1px solid #f00;
width: 300px;
height: 100px;
margin: 180px auto;
position: relative;
}
<div class="main">
<div class="content" id="edit-content" contenteditable="true">
Type your text here
</div>
</div>
<button class="temp-title" id="add_heading1" onclick="pasteHtmlAtCaret(heading);">Heading</button>