Javascript HTML-更改选定内容中文本的样式

Javascript HTML-更改选定内容中文本的样式,javascript,html,styles,selection,Javascript,Html,Styles,Selection,是否可以更改选定内容中文本的stlye <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.

是否可以更改选定内容中文本的stlye

<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>

这是用于测试选择的文本

函数mouseUp(){ var selection=window.getSelection(); 警报(selection.toString()); //我能说出选择的第一个字符的颜色吗? }
您需要将元素中的第一个字符(例如
span
)包装起来,然后对该元素应用一些css或类。

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

(摘自:)

编辑: 要更改样式,下面是一个简单的示例

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

这是用于测试选择的文本

函数环绕选择(){ var span=document.createElement(“span”); span.style.fontwweight=“bold”; span.style.color=“绿色”; if(window.getSelection){ var sel=window.getSelection(); 如果(选择范围计数){ var range=sel.getRangeAt(0.cloneRange(); 范围。周围内容物(跨度); 选择removeAllRanges(); 选择添加范围(范围); } } }
试试这个-它可以工作:点击“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>

这是用于测试所选内容的文本

函数mouseUp(){ var first_L=document.getElementById(“第一个字母”); first_L.style.color=“蓝色”; }
这是如何包装的:将代码放在此处我问题中的代码提供了一个字符串(所选文本)。显然,我可以用这个字符串创建一个新的span元素;但我的问题是如何设置实际选定文本的样式?(在我的示例中的p元素中)。您可以访问selection.extentNode.parentNode以使用格式正确的span替换selection(使用jQuery append()函数),但这将更加复杂,因为一个选择可以跨越多个节点(这只是您可能遇到的第一个问题)。仅在非常简单的场景中很容易做到这一点
<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>