是否可以更改所选文本的样式?
<p onmouseup="mouseUp()">This is a text for testing the selection</p>
<script>
function mouseUp() {
var selection = window.getSelection();
alert(selection.toString());
//can I cahnge the color of e.g. the first character of the selection?
}
</script>
最佳答案
我已经遇到过这个问题,并且发现以下解释和实现很有用:
function surroundSelection(element) {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(element);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
(取自:Wrapping a selected text node with span)
编辑: 也改变风格,这里是一个简单的例子
<p onmouseup="surroundSelection()">This is a text for testing the selection</p>
<script>
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
关于javascript - HTML - 更改选择中文本的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22268137/