Color change of the selected text in HTML

别来无恙 提交于 2021-02-08 07:34:21

问题


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

    }
}

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.


回答1:


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

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



回答2:


I know that this is a JS question, but there is a CSS selector which allows you to do this.

::selection {
  color: red;
}

If the browser considers that you've made a choice which is not accessible, it might override your colours. Not everything can be styled in this way, but colours and background colours can.

More information:

  • ::selection on CSS Tricks
  • ::selection on MDN


来源:https://stackoverflow.com/questions/29845266/color-change-of-the-selected-text-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!