Change text selection highlight with JS

后端 未结 1 1836
栀梦
栀梦 2021-01-06 01:37

For standard browsers you can use something like this to change the coloring of selected text:

div.txtArea::selection {
 background: transparent;
}

div.txtA         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 02:12

    There's no DOM interface for manipulating pseudo-classes. The only thing you can do is add the rules to a stylesheet. For instance:

    // Get the first stylesheet 
    var ss = document.styleSheets[0]
    
    // Use insertRule() for standards, addRule() for IE
    if ("insertRule" in ss) {
        ss.insertRule('div.txtArea::-moz-selection { background: transparent; }', 0);    
        ss.insertRule('div.txtArea::selection { background: transparent; }', 0);    
        ss.insertRule('div.txtArea::-webkit-selection { background: transparent; }', 0);    
    }
    

    You can access and change rules using stylesheet.cssRules[index].style, stylesheet.rules[index].style for IE, which is where it gets a little more complicated.

    I didn't include an IE6-8 example using addRule() because those versions of IE don't support ::selection.

    0 讨论(0)
提交回复
热议问题