因为你不能在 textarea 里面设置文本样式,
以下是使用内容可编辑的 div 的解决方案:
(灵感来自我对另一个问题的解决方案:Change font for selected text using JavaScript)
function changeStyle(style) {
var sel = window.getSelection(); // Gets selection
if (sel.rangeCount) {
// Creates a new element, and insert the selected text with the chosen style
var e = document.createElement('span');
e.classList.add(style.value); // Selected style (class)
e.innerHTML = sel.toString(); // Selected text
// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
var range = sel.getRangeAt(0);
range.deleteContents(); // Deletes selected text…
range.insertNode(e); // … and inserts the new element at its place
}
}
.editable {
width: 360px;
height: 120px;
border: 1px solid #ccc
}
.editable .span-0{ /* Added to reset styles correctly */
font-weight: normal; /* Reset b */
text-decoration: none; /* Reset u */
font-style: normal; /* Reset i */
}
.editable .span-b{
font-weight: bold;
}
.editable .span-u{
text-decoration: underline;
}
.editable .span-i{
font-style: italic;
}
Highlight text and change style
None
Bold
Underlined
Italic
Some Content
(我添加了其他样式选项...只是因为!)
我希望它有所帮助!