JavaScript transition with the display property?

前端 未结 3 1193
粉色の甜心
粉色の甜心 2021-01-28 01:54

Can I make a certain element fade in when I hover over another one, and make it fade out when my mouse isn\'t on the element anymore?

I tried adding a transition

3条回答
  •  温柔的废话
    2021-01-28 02:48

    At first, I thought about soktinpk's solution. Opacity can be animated with css so it's the best bet.

    However, it takes up the space even when it is not shown. To prevent that, you could make it position:absolute. But even then, elements behind it will not be clickable.

    Here is a more robust solution with a combination of @soktinpk's ideas

    To prevent that, hide it with display:none when it is not visible.

    Edit

    Actually, visibility:hidden seems to work better when fading back in.

    HTML

    CSS

    #button {
        background-color: rgb(0,0,100);
        width: 100px;
        height: 50px;
        margin-top: 50px;
        margin-left: 50px;
        position:relative; // All absolutely positioned elements inside are relative to this element
    }
    
    #menu {
        background-color: rgb(0,100,0);
        width: 200px;
        height: 100px;
        opacity:0;
        visibility:hidden;
        transition: opacity 1s;
        -webkit-transition: opacity 1s;
        -moz-transition: opacity 1s;
        -o-transition: opacity 1s;
        position:absolute; // So that it displays at the right position
        top:100%;
        left:0;
    }
    

    JS

    var time_out;
    var menu = document.getElementById("menu");
    
    function showMenu() {
        clearTimeout(time_out);
        menu.style.visibility = "visible";
        menu.style.opacity = 1;
    }
    
    function hideMenu() {
        clearTimeout(time_out);
        menu.style.opacity = 0;
        // This will hide it when the animation is over
        time_out = setTimeout(function(){menu.style.visibility = "hidden";},1000);
    }
    

    JS Fiddle Demo

提交回复
热议问题