Set the text selection color with jQuery. Demo not working

情到浓时终转凉″ 提交于 2019-12-14 03:46:24

问题


http://jsfiddle.net/uKdPM/

I've set the ::selection color in css, so when you highlight the text on the screen, the color of the text is pink. I'm trying to now override that color through jQuery when the page loads. Seems like it should be super simple. But it's not working for me.


回答1:


I believe if you want to achieve this kind of effect, you need to apply the color change based on a CSS class. I forked your jsfiddle, and heres the result

Although i think your question is interesting, im having a difficult time figuring where this can be put to practical use. Do you want to change the theme on the fly?




回答2:


According to this question you can't change the highlight color of a selection, because there isn't a DOM interface for manipulating pseudo classes. What you could do is to change the class of the element.




回答3:


I had the same problem, and I stumbled upon this question. The solution can be just adding a <style> tag with css properties into the document body.

$('<style> p::selection{ background-color:#000; } p::-moz-selection{ background-color:#000; }</style>').insertAfter('body *:last');

This might not be the most elegant way to do it, but at least it works.




回答4:


::selection is a CSS pseudo-class, not a jquery selector !

You can't do this $('p::selection').css({color: "#3c3"}) and expect the text selection color to be changed.


  • $(<selector>) allows you to select dom elements in flexible way, using IDs, css classes, attributes...

  • :hover, :after... ::selection are CSS-pseudo selector which allows you to style elements.

Even though the syntax of a jquery selector can look the same as a pseudo-class css, they are different.


By the way, it is not possible to change programmatically the style of css pseudo-classes (like :hover...).




回答5:


If you can change to using classes instead of directly setting the colour from JavaScript, then do that because it's much simpler.

Otherwise, see this question: Setting CSS pseudo-class rules from JavaScript

Using the library provided in this answer:

jss('p::selection', {
    color: '#3c3'
});

http://jsfiddle.net/thirtydot/uKdPM/9/



来源:https://stackoverflow.com/questions/8473676/set-the-text-selection-color-with-jquery-demo-not-working

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