简体   繁体   中英

jQuery: Changing the hover color with a color picker

I would like to change the hover color with a color picker.

This is what I have tried:

 // First Try $("input[type=color]").change(function(e) { var pickedColor = e.target.value; // $("body").css("background-color", pickedColor); $("div:hover").css("color", pickedColor); }); // Second Try $("input[type=color]").change(function(e) { var pickedColor = e.target.value; // $("body").css("background-color", pickedColor); $(".hover").css("color", pickedColor); }); $("div").hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
 body { display: flex; font-size: 30px; font-family: Arial; cursor: default; } div { color: red; padding: 10px; } div:hover { color: orange; }.hover { color: blue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>Hello</div> <input type="color">

Unfortunately, both does not work. The color picker makes it a bit complex, I guess. Could somebody help me please?

Would be very thankful!

In the 2nd (using jquery hover() ), you're adding .hover class to the div, which is working fine, but the css div:hover is take precedence so showing in orange

The (updated) issue with the colour being dynamic (from a colour picker) means you can't use css classes. (You can, but it's a bit hacky where you add a <style> element: https://stackoverflow.com/a/21051833/2181514 , but not really usable if it can change multiple times).

You also can't style :pseudo (like :hover ) elements directly.

Leaving the option to use .hover() .

 // Setup the colour $("input[type=color]").change(function(e) { var pickedColor = e.target.value; $("div.hoverme").data("hovercolour", pickedColor); }); // Set the colour on hover/unhover $("div").hover(function() { var pickedColor = $(this).data("hovercolour"); $(this).css("color", pickedColor); }, function() { var normalColor = $(this).data("normalcolour") $(this).css("color", normalColor); });
 body { font-size: 30px; } div { color: red; padding: 10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="hoverme" data-hovercolour="orange" data-normalcolour="red">Hello</div> <input type="color">

Here, rather than use a global variable for the colours, I've stored the two colours in data- attributes along with the default orange - which jquery can read when it's time to hover

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