Change text selection highlight with JS

删除回忆录丶 提交于 2019-11-30 21:01:21

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.

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