最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change text selection highlight with JS - Stack Overflow

programmeradmin8浏览0评论

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

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

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

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

But I need to do this with JavaScript instead.

My users can select text and then change the color. While they are selecting another color it updates the color constantly. Since the text is selected they can't see what the color looks like. I need to change the selection style of my targeted element to be transparent only during mouseover of the color changer.

I have tried a few things including:

$('div.txtArea').css({
    'selection': 'transparent',
    '-moz-selection': 'transparent',
    '-webkit-selection': 'transparent'
});

Is there a way to do this with javascript?

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

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

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

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

But I need to do this with JavaScript instead.

My users can select text and then change the color. While they are selecting another color it updates the color constantly. Since the text is selected they can't see what the color looks like. I need to change the selection style of my targeted element to be transparent only during mouseover of the color changer.

I have tried a few things including:

$('div.txtArea').css({
    'selection': 'transparent',
    '-moz-selection': 'transparent',
    '-webkit-selection': 'transparent'
});

Is there a way to do this with javascript?

Share Improve this question edited May 30, 2013 at 14:13 Mechlar asked Aug 6, 2010 at 21:39 MechlarMechlar 5,00414 gold badges60 silver badges83 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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 plicated.

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

发布评论

评论列表(0)

  1. 暂无评论