HTML - 更改选择中文本的样式

时间:2014-03-08 10:33:31

标签: javascript html styles selection

是否可以更改选区中文字的样式?

3 个答案:

答案 0 :(得分:2)

我已经遇到过这个问题,并发现以下解释和实现很有用:

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);
        }
    }
}

(取自: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);
        }
    }
}

答案 1 :(得分:0)

您需要将第一个字符包装在元素中(例如span),然后将一些css或类应用于该元素。

答案 2 :(得分:0)

试试这个 - 它有效:点击“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>