是否可以在选择中更改文本的稳定?
<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>
我已经遇到了这个问题,并找到了以下解释和实现。
http://jsfiddle.net/vrcvn/
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);
}
}
}
(从:将选定的文本节点与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);
}
}
}
您需要将第一个字符包装在元素中(例如span
),然后将一些CSS或类应用于该元素。
尝试一下 - 它可以工作:单击" t",它将更改为蓝色
<p onclick="mouseUp()">
<span id="first_Letter">T</span>his is a text for testing the selection
</p>
<script>
function mouseUp() {
var first_L = document.getElementById("first_Letter");
first_L.style.color = "blue";
}
</script>