Continuous CSS rotation animation on hover, animated back to 0deg on hover out

后端 未结 7 1547
温柔的废话
温柔的废话 2020-11-30 22:26

I have an element that spins when you hover over it indefinitely. When you hover out, the animation stops. Simple:

@-webkit-keyframes rotate {
    from {
            


        
7条回答
  •  Happy的楠姐
    2020-11-30 22:44

    Cross browser compatible JS solution:

    var e = document.getElementById('elem');
    var spin = false;
    
    var spinner = function(){
    e.classList.toggle('running', spin);
    if (spin) setTimeout(spinner, 2000);
    }
    
    e.onmouseover = function(){
    spin = true;
    spinner();
    };
    
    e.onmouseout = function(){
    spin = false;
    };
    body { 
    height:300px; 
    }
    #elem {
    position:absolute;
    top:20%;
    left:20%;
    width:0; 
    height:0;
    border-style: solid;
    border-width: 75px;
    border-color: red blue green orange;
    border-radius: 75px;
    }
    
    #elem.running {
    animation: spin 2s linear 0s infinite;
    }
    
    @keyframes spin { 
    100% { transform: rotate(360deg); } 
    }

提交回复
热议问题