javascript - 在按钮单击时在内容可编辑的 div 内的插入符号位置添加内容
问题描述
我正在尝试使用按钮单击和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>
解决方案
推荐阅读
- c# - C#位图活动表单>对象引用未设置为对象的实例
- amazon-web-services - 无法获取 AWS 云提供商。GetCloudProvider 返回
反而 - php - mkdir 与 php 7.3 和 centos 7
- android - 如何重新连接我的 Firebase 实例以便可以读写?
- java - 在 Android Studio 中更改使用 renderManager 的应用程序中的字体
- angular - 根据父组件中的过滤数据刷新子组件中的表格
- java - 使用 1 行代码实例化和初始化对象数组
- javascript - JSON 到 PHP API 没有发生
- jenkins - 在上游作业中添加的两个参数中只有一个在下游作业中起作用
- c++ - 为什么 glm::mat3 和 glm::value_ptr 创造了一个穿越时间和宇宙的黑洞,并且正在破坏我脑海中任何可能的逻辑?