首页 > 解决方案 > 悬停时触发动画

问题描述

我试图在 img class=.nav-icon 悬停时触发所有动画。目前动画在页面加载时播放一次,我不知道如何将它绑定到:hover 或 onmouseover="function"。

HTML

<nav id='nav-animation'>
   <img class='nav-icon' src='images/nav-icon.png' alt='NAVIGATION'>
      <ul class="nav-links">
         <li id='li-1'><a href='index.html'>home</a></li>
         <li id='li-2'><a href='works/works.html'>works</a></li>
         <li id='li-3'><a href='thoughts/thoughts.html'>thoughts</a></li>
         <li id='li-4'><a href='about/about.html'>about</a></li>
       </ul>
</nav>

CSS

/* NAV ANIMATION */

#li-1 {
    position: relative;
    animation: li-1 .5s ease 0s alternate 1 forwards running;
}
@-webkit-keyframes li-1 {
  0% {left: 400px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

#li-2 {
    position: relative;
    animation: li-2 .5s ease .3s alternate 1 both running;
}
@-webkit-keyframes li-2 {
  0% {left: 280px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

#li-3 {
    position: relative;
    animation: li-3 .5s ease .7s alternate 1 both running;
}
@-webkit-keyframes li-3 {
  0% {left: 190px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

#li-4 {
    position: relative;
    animation: li-4 .5s ease 1.1s alternate 1 both running;
}
@-webkit-keyframes li-4 {
  0% {left: 80px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

标签: javascripthtmlcss

解决方案


我不完全确定您想要的效果,但您应该能够通过选择 li 元素作为 img 导航元素的兄弟元素而无需使用 Javascript 来做到这一点。

在这个片段中,我们已经有了 li 元素——但如果需要的话,它们可以放在右边的站点之外。当 img 悬停在上面时,将为 li 元素设置动画。

当然,这有很多变体,例如,当整个包含元素未悬停时,不保留 li 元素。

/* NAV ANIMATION */

#nav-animation img:hover ~ ul #li-1 {
    animation: li-1 .5s ease 0s alternate 1 forwards running;
}
#nav-animation ul li {
    position: relative;
}
@keyframes li-1 {
  0% {left: 400px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1; display: block;}
}

#nav-animation:hover img:hover ~ ul #li-2 {
    animation: li-2 .5s ease .3s alternate 1 both running;
}
@keyframes li-2 {
  0% {left: 280px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

#nav-animation:hover img:hover ~ ul #li-3 {
    animation: li-3 .5s ease .7s alternate 1 both running;
}
@keyframes li-3 {
  0% {left: 190px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}

#nav-animation:hover img:hover ~ ul #li-4 {
    animation: li-4 .5s ease 1.1s alternate 1 both running;
}
@keyframes li-4 {
  0% {left: 80px; top: 0px; opacity: 0;}
    100% {left: 0px; top: 0px; opacity: 1;}
}
<nav id='nav-animation'>
   <img class='nav-icon' src='images/nav-icon.png' alt='NAVIGATION'>
      <ul class="nav-links">
         <li id='li-1'><a href='index.html'>home</a></li>
         <li id='li-2'><a href='works/works.html'>works</a></li>
         <li id='li-3'><a href='thoughts/thoughts.html'>thoughts</a></li>
         <li id='li-4'><a href='about/about.html'>about</a></li>
       </ul>
</nav>


推荐阅读