【问题标题】:Change text selection highlight with JS使用 JS 更改文本选择突出显示
【发布时间】:2011-03-26 13:45:11
【问题描述】:

对于标准浏览器,您可以使用类似的方法来更改所选文本的颜色:

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 做到这一点?

【问题讨论】:

    标签: javascript jquery css selection textselection


    【解决方案1】:

    没有用于操作伪类的 DOM 接口。您唯一能做的就是将规则添加到样式表中。例如:

    // 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].stylestylesheet.rules[index].style 访问和更改规则稍微复杂一点。

    我没有包含使用 addRule() 的 IE6-8 示例,因为这些版本的 IE 不支持 ::selection

    【讨论】:

    • 谢谢,这就是我要做的。我已经编写了一个用于操作样式表的跨浏览器解决方案。我希望不必使用它(只是为了保持内联方法)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多