Set the text highlight color using jQuery. Demo doesn't work

http://jsfiddle.net/uKdPM/

I set the ::selection color to css, so when you select text on the screen, the text color is pink. I am trying now to override this color through jQuery when the page loads. It sounds like it should be super easy. But this does not work for me.

+4
source share
5 answers

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

Although I think your question is interesting, it is difficult for them to determine where this can be applied for practical use. Do you want to change the theme on the fly?

+5
source

According to this question, you cannot change the highlight color of the selection, because there is no DOM interface for manipulating pseudo-classes. What you can do is change the class of the element.

+2
source

I had the same problem and stumbled upon this question. The solution may simply be to add a <style> with css properties to the body of the document.

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

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

+1
source

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

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


  • $(<selector>) allows you to flexibly select dom elements using identifiers, css classes, attributes ...

  • :hover :after ... ::selection is a CSS pseudo selector that allows you to style .

Although the syntax of the jquery selector may look the same as the css pseudo-class, it is different.


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

0
source

If you can switch to using classes instead of directly setting the color from JavaScript, do it because it's a lot easier.

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/

0
source

Source: https://habr.com/ru/post/1385880/


All Articles