HTML中选定文本的颜色更改 [英] Color change of the selected text in HTML

查看:91
本文介绍了HTML中选定文本的颜色更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想突出显示功能,它将使用Javascript更改所选文本的颜色.我正在使用以下方法.

I want to highlight feature which will change the color of the selected text using Javascript. I am using the following method.

function android_selection_highlight(replacrmenthtml){
    try {
        if (window.getSelection) {
            sel = window.getSelection();
            var range = sel.getRangeAt(0);

            var selectionStart = $("<span style=\"color:red\">");
            var startRange = document.createRange();
            startRange.setStart(range.startContainer, range.startOffset);


            var selectionEnd = $("</span>");
            var endRange = document.createRange();
            endRange.setStart(range.endContainer, range.endOffset);

            startRange.insertNode(selectionStart[0]);
            endRange.insertNode(selectionEnd[0]);
        }
    }
    catch (e) {

    }
}

但是当我调用该方法时,它给了DOM异常.我认为,当我在所选文本的前面插入开始跨度标签时,由于当时没有结束标签,这正在破坏DOM结构.如何解决这个问题?

But it is giving DOM exception when I am calling the method. I think that when I am inserting starting span tag in front of the selected text, it is disrupting the DOM structure as there is no end tag at that moment. How to solve this problem?

已编辑:会有一个高亮按钮.选择文本后,如果用户单击突出显示按钮,则所选文本的文本颜色将发生变化.

Edited: There will a highlight button. Selecting the text, if user click on the highlight button, the text color of the selected text will change.

推荐答案

如果选择要更改颜色,请使用此代码.

if on select u want to change color use this code.

    ::-moz-selection { color: red;}
    ::selection { color: red; }

这篇关于HTML中选定文本的颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆