How to show random color on hover in CSS?

前端 未结 5 1472
清歌不尽
清歌不尽 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:47

    Here is how I would do it with javascript and jquery (not required but simpler).

    html:

    javascript:

    $('#random').on('mouseover',function() {
        var color = '#'+Math.floor(Math.random()*16777215).toString(16);
        var colorString = '0px 0px 30px 0px ' + color;
        $('#random').css('box-shadow',colorString);
        $('#random').css('-webkit-box-shadow',colorString);
        $('#random').css('-mox-box-shadow',colorString);
    });
    

    css:

    #random {
        width: 200px;
        height: 200px;
        border: 1px solid black;
    }
    

    Here is the updated working fiddle: https://jsfiddle.net/6n0tk3a3/1/

    EDIT

    Here is the same thing using pure javascript - no jquery - and your provided class names and css.

    First html:

    
    
    
    

    Javascript:

    var menuBoxes = document.getElementsByClassName('MenuBox');
    for (var i = 0; i < menuBoxes.length; i++) {
        menuBoxes[i].onmouseover = function(e) {
            var color = '#'+Math.floor(Math.random()*16777215).toString(16);
            var colorString = '0px 0px 30px 0px ' + color;
            this.style['box-shadow'] = colorString;
            this.style['-webkit-box-shadow'] = colorString;
            this.style['-moz-box-shadow'] = colorString;
        }  
    }
    

    Since I used your css I won't post it. Here is the working fiddle: https://jsfiddle.net/6n0tk3a3/2/

    In your comment you said you want them all in the same file. Though you can do this I would advise against it as it is usually considered bad practice. If you do decide to do it then make sure your javascript goes right before the closing body tag so that all the elements on the page are loaded before it tries to bind to any of them.

    Edit #2

    If you want the color to box shadow to disappear once your mouse is no longer hovering add this to the for loop:

    menuBoxes[i].onmouseout = function(e) {
        this.style['box-shadow'] = "none";
        this.style['-webkit-box-shadow'] = "none";
        this.style['-moz-box-shadow'] = "none";
    }
    

    Here is a working fiddle: https://jsfiddle.net/6n0tk3a3/25/

提交回复
热议问题