如何解决将子元素附加到内容可编辑的div之后,重点关注子元素
我有一个将span
添加到可编辑内容的div
的按钮。我想专注于span
,以便用户可以更改其内容。实际上,此代码是所见即所得的编辑器,因此用户可以在可编辑的div
内键入一些文本,然后按按钮以键入突出显示的文本。
这是我的代码:
$("#btn").click(function () {
var newSpan = document.createElement("span");
newSpan.classList.add("highlight");
newSpan.innerHTML = ""; // the span must be empty
var myDiv = document.getElementById("editable-div");
myDiv.appendChild(newSpan);
newSpan.focus();
// here I expect to be able to change the content of the newSpan,// but I'm still inside the myDiv element.
// <div id="editable-div" contenteditable="true">
// <span class="highlight">
// I WANT TO BE HERE AFTER APPENDING THE SPAN
// </span>
// </div>
});
CSS:
.highlight {
background-color: yellow;
}
HTML:
<div id="editable-div" contenteditable="true"></div>
<button id="btn">Highlight</button>
注意:如果范围不是空的,代码可以正常工作,但是我想附加一个空的范围。
解决方法
这是您要实现的目标的摘要:
var timeout;
$("#btn").click(function() {
let span = "<span class='highlight' contentEditable='true'></span>";
$("#editable-div").prop("contentEditable",false);
$("#editable-div").append(span);
$("#editable-div span:last-child").focus();
$("#editable-div span").on("input",function() {
clearTimeout(timeout);
let breakOf = 1500;
timeout = setTimeout(function() {
$("#editable-div").prop("contentEditable",true);
},breakOf);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editable-div" contentEditable='true'>
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</div>
<button id="btn">Button</button>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。