我有一个contentEditable div,我希望用户可以在其中按下一个按钮并使他们选择的文本变为粗体。现在,我的操作方式是window.getSelection.toString();
获取所选内容中的文本,并将其替换为具有相同内容但window.getSelection.toString()
不包含任何HTML元素的粗体元素。
为了解决这个问题,我想在选择的开头和结尾添加HTML标记。我在堆栈溢出中找到了其他答案,可以将HTML添加到选择的开头和结尾,但是这些答案将div或span附加到开头和结尾,从而导致<div><b></div> Selection text <div></b></div>
粗体标签与实际选择文本分离。
我没有使用任何库,并且希望不必使用任何一个。
这是一个有关如何使用window.getSelection和Range API获取(或更改)HTML内容的示例,现在是推荐的方法,并且以前还没有提供更广泛的支持:https:// caniuse。 com /#feat = selection-api
首先获取html示例:
function butclick() {
var ediv = document.getElementById('your-editable-div'); // get a reference to the editable div
var range = window.getSelection().getRangeAt(0); // get the range
var aux = document.createElement("span"); // create an auxiliar tag
aux.appendChild(range.cloneContents()); // clone (so the original selection is not removed or replaced) and insert it into the auxiliar dom tag
alert(aux.innerHTML); // now you can get the innerHTML of the aux tag
}
<div contentEditable id="your-editable-div" style="border: solid 1px black; padding: 2px; margin: 5px;">This is <b>an editable</b> div with html tags</div>
<button onclick="butclick()">get html of selected area</button>
以及如何将html更改为其他html:
function butclick() {
var ediv = document.getElementById('your-editable-div'); // get a reference to the div
ediv.focus(); // optional: focus again the editable div so you can continue editting
var range = window.getSelection().getRangeAt(0); // select first of the selections
var aux = document.createElement("span"); // create an aux html span tag
aux.style.backgroundColor = "red"; // apply some new style
aux.appendChild(range.extractContents()); // extract (so the original contents are removed) and inyect into aux tag
range.insertNode(aux); // finally insert back again the edited aux node back into the editable div, this includes the aux tag itself, but you can insert whatever dom tag you want, or various tags, or even only the children
}
<div contentEditable id="your-editable-div" style="border: solid 1px black; padding: 2px; margin: 5px;">This is <b>an editable</b> div with html tags</div>
<button onclick="butclick()">replace html with other html</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句