简体   繁体   中英

change background color and hover colors on refresh

I want to change the website logo color and the hover color of the buttons every time a user refreshes the pages. The colors have to be coordinated. Website Link The logo is actually an image with a transparent region, where I can put any background color I want.

Someone had a similar problem here: JQuery Random Background color and color, on 2 div's

This is the javascript that I made based on that thread:

$(document).ready(function(){
   var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];                
   var rand = Math.floor(Math.random()*colors.length);           
   $('#logo').css("background-color", colors[rand]);
   $('.cbp-ig-grid').css("background-color", colors[rand]);
});

.cbp-ig-grid changes the background color properly, but I want the color to appear only on hover. The .cbp-ig-grid class has this hover property:

.cbp-ig-grid li > a:hover { background-color:#71e271;}

The problem is that if I change the javascript code '.cbp-ig-grid' with '.cbp-ig-grid li > a:hover' it stops working. I have no experience with Javascript, so I'm definitely doing something wrong.

Try using hover() method :

$('.cbp-ig-grid').hover(function() {
   $(this).css("background-color", colors[rand]); 
});

i would be more inclined to print out a <style> sheet using javascript than add hover() events using jquery

<script>
var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];                
var rand = Math.floor(Math.random()*colors.length);
var head = document.head,
    style = document.createElement('style');

var css = '#logo { background-color: ' + colors[rand] + '; } ';
    css += '.cbp-ig-grid li > a:hover { background-color: ' + colors[rand] + '; } ';

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);
</script>

Use this

$('.cbp-ig-grid  li > a').hover(function(){
$(this).css("background-color", colors[rand]);
});

What you're doing is this:

replace $('.cbp-ig-grid').css("background-color", colors[rand]);

with $('.cbp-ig-grid li > a:hover').css("background-color", colors[rand]);

is that correct? anyways, you can't control the hover state with a jQuery selector: $('.cbp-ig-grid')

you can achieve this by setting a event handler with a function like this:

$(document).ready(function(){
   var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];                
   var rand = Math.floor(Math.random()*colors.length);           
   $('#logo').css("background-color", colors[rand]);

   $(".cbp-ig-grid li").on("mouseover", function () {
       $(this).css("background-color", colors[rand]);
   });

}

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