【问题标题】:Opposite of CSS Selector:hover? [closed]CSS 选择器的对面:hover? [关闭]
【发布时间】:2021-08-19 03:09:26
【问题描述】:

如果我想在用户将鼠标悬停在<a> 标签上时制作动画,我只需要:hover

但是,如果我想在用户将鼠标从<a> 移开时执行某些操作,则将适用规则。 我不想在悬停之前播放动画,就像在 a { animation: name 1s linear reverse } 中一样,但我希望它播放 在用户停止悬停之后。

【问题讨论】:

  • 你需要 javascript。
  • 或使用mouseleave。
  • 也许可以使用过渡而不是动画来做到这一点,但这取决于您要制作动画的具体内容和方式。这并不总是可能的。如果你能指定这个会有所帮助。

标签: html css css-selectors


【解决方案1】:

没有 js 的方法是将要动画的元素包装在一个 div 中,并使用关键帧将该 div 设置为visibility: hidden。然后将动画设置为与您正在制作动画的元素的实际动画相同的时间。这将在初始加载动画期间隐藏元素。然后,您可以使用:not 选择器在每次停止悬停后对其进行动画处理。

#container {
  animation: hidden 1s linear 1;
}
#block {
  width: 50px;
  height: 50px;
  background: red;
  
}

div:not(:hover) {
  animation: grow 1s linear; 
}

@keyframes grow {
  to {width: 100px;}
}

@keyframes hidden {
  from {visibility: hidden;}
  to {visibility: hidden;}
}
<div id="container">
<div id="block"></div>
</div>

【讨论】:

    【解决方案2】:

    您可以使用 javascript 在元素上添加 mouseover 事件,然后在附有动画的 event.target 上添加 class .如果您希望这是无限的,就用户每次鼠标移出而言,您可以设置 setTimeout 并使用相同的 CSS 动画持续时间从元素中删除该类。

    //get the element from the DOM using its id attribute
    const hoverme = document.getElementById('hoverme')
    
    // create an event listener for mouseout  
    // and pass the event into the function --> e
    hoverme.addEventListener('mouseout', function(e) {
      // now get the current event.target --> e.target
      // and add the class that has the animation attached to it
      e.target.classList.add('anim-class')
      // remove the animation class using setTimeout
      // with a duration that is the same as that set in the 
      // css animation, in my example it is 2 seconds --> 2000ms
      setTimeout(()=>{
        e.target.classList.remove('anim-class')
      }, 2000) //<-- 2 seconds or 2000ms
    })
    #hoverme {
      color: #000;
    }
    
    #hoverme:hover {
      color: #0FF;
    }
    
    .anim-class {
      animation: rotate 2s ease-in-out;
    }
    
    @keyframes rotate {
      from {
        transform: rotate(360deg);
      }
      to {
        transform: rotate(0deg);
      }
    }
    <div id="hoverme">
      Hover over this
    </div>

    【讨论】:

      【解决方案3】:

      hover 的反义词其实是初始状态 所以你就这样走

      .class{
      // not hover
      }
      
      .class:hover{
      // when hover
      }
      

      【讨论】:

      • 是的,但是如果我播放动画,它将在站点加载或元素加载时运行。
      • 啊,我明白了,您将需要另一个 css 类,然后在该元素上添加一个事件监听器,以便在鼠标离开后应用样式
      • 请参阅stackoverflow.com/questions/11703241/… 了解有关事件与状态的说明。
      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 2021-03-21
      • 2015-07-19
      • 2010-09-20
      • 2012-04-13
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多