How to show random color on hover in CSS?

前端 未结 5 1516
清歌不尽
清歌不尽 2021-01-17 16:00

I have this CSS code that only displays one color (blue) when there\'s a mouse hover.

.MenuBox {
    transition: all 1.0s ease;
    -moz-border-radius:30px;
         


        
5条回答
  •  时光取名叫无心
    2021-01-17 16:45

    This javascript sets up an array of colors, then randomly selects one of them and applies it on hover. It then returns it to normal when you stop hovering.

    var colors = ['blue','green','red','purple','yellow'];
    
    $('.MenuBox').mouseenter(function() {
        var rand = colors[Math.floor(Math.random() * colors.length)];
        $(this).css('background-color', rand);
    });
    
    $('.MenuBox').mouseleave(function() {
        $(this).css('background-color', '');
    });
    

提交回复
热议问题