对于标准浏览器,您可以使用类似这样的方法来更改所选文本的颜色:
div.txtArea::selection {
background: transparent;
}
div.txtArea::-moz-selection {
background: transparent;
}
div.txtArea::-webkit-selection {
background: transparent;
}
但我需要改用 JavaScript 来执行此操作。
我的用户可以选择文本然后更改颜色。当他们选择另一种颜色时,它会不断更新颜色。由于选择了文本,他们看不到颜色的样子。我需要将目标元素的选择样式更改为仅在鼠标悬停在颜色转换器上时透明。
我尝试了一些方法,包括:
$('div.txtArea').css({
'selection': 'transparent',
'-moz-selection': 'transparent',
'-webkit-selection': 'transparent'
});
有没有办法用 javascript 做到这一点?
最佳答案
没有用于操作伪类的 DOM 接口(interface)。您唯一可以做的就是将规则添加到样式表中。例如:
// 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);
}
您可以使用 stylesheet.cssRules[index].style 访问和更改规则,对于 IE,stylesheet.rules[index].style稍微复杂一点。
我没有包含使用 addRule() 的 IE6-8 示例,因为这些版本的 IE 不支持 ::selection
。
关于javascript - 使用 JS 更改文本选择突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3427981/