问题描述
我有一个将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>