简体   繁体   中英

Change text colour to background colour with jquery

Using Wordpress editor to change text colour, is there a way I can then use jquery to force it to make this the background colour instead.

This is what wp renders when I change the colour of the text:

<p>
   <span style="color: #ff0000;">
      <a style="color: #ff0000;" href="#">Link name</a>
   </span>
</p>

I want the background to be whatever colour I choose instead.

Something along the lines of, but I'm stuck. [THE SELECTED COLOUR] is just a placeholder so you can see what I'm trying to do.

$("p span a").css("background-color","[THE SELECTED COLOUR]");

How about this, where you iterate though them all

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <span style="color: #ff0000;"> <a style="color: #ff0000;" href="#">Link name</a> </span> </p> <p> <span style="color: #0000ff;"> <a style="color: #0000ff;" href="#">Link name</a> </span> </p> <script> $("p span a").each(function( index ) { $( this ).css("background-color", $( this ).css("color")); $( this ).css("color", "white"); }); </script> 

Or, as A.Wollf suggests in his comment, use a function

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <span style="color: #ff0000;"> <a style="color: #ff0000;" href="#">Link name</a> </span> </p> <p> <span style="color: #0000ff;"> <a style="color: #0000ff;" href="#">Link name</a> </span> </p> <script> $("p span a").css({"background-color":function(){ return $(this).css('color'); }, "color": "white"}); </script> 

Hope this will be useful

$("p span a").css("background-color","green");

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM