如何使用纯javascript触发元素上的悬停效果?

时间:2015-07-02 21:01:18

标签: javascript jquery css3 css-animations css-transforms

用css3动画来玩弄 检查http://codepen.io/rokki_balboa/pen/eNVEyq

<section>
        <div></div>
        <div></div>
</section>
<a href="#" id="trigger">Change</a>


@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300);
    * {
            margin: 0;
            padding: 0;
    }

html {
        overflow: hidden;
}

body {
        height: 100vh;
        width: 100vw;
        background-color: #000;
        position: relative;
}

section {
        width: 100%;
        height: 100%;
        position: relative;
        perspective: 500px;
}

section:hover {
        transform-style: preserve-3d;
        animation: cool 5s ease-in-out forwards;
}

@keyframes cool {
        0% {
                transform: perspective(1000px) translateZ(0px);
        }
        45% {
                transform: perspective(1000px) translateZ(-400px);
        }
        55% {
                transform: perspective(1000px) translateZ(-400px) rotateY(.5turn);
        }
        100% {
                transform: perspective(1000px) translateZ(-400px) rotateY(.5turn) translateZ(-400px);
        }
}

div {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
}

div:nth-child(1) {
        background: url(http://i.imgur.com/dLBSLQu.jpg) top center no-repeat;
        background-size: cover;
}

div:nth-child(2) {
        background: url(http://i.imgur.com/uL0mXb6.jpg) top center no-repeat;
        background-size: cover;
        transform: rotateY(.5turn);
        backface-visibility: hidden;
}

#trigger {
        position: absolute;
        bottom: 10px;
        left: 10px;
        color: #fff;
        font-size: 14px;
}

.ghoster {
        display: none;
}

正如你可以看到它在悬停部分时有效。但我的目标是在您单击锚点时触发悬停在部分上。

1。你点击更改锚点
 的 2。动画来自部分元素
 3.再次点击
 4.动画又来了

我不知道如何实现这样的结果。你能帮我吗
附:如果你在纯粹的javascript上做它会更好。

1 个答案:

答案 0 :(得分:1)

CSS

<style>
section.activateHover
{
    transform-style: preserve-3d;
    animation: cool 5s ease-in-out forwards;
}
</style>

HTML

<section id="sectionToChange">
    <div></div>
    <div></div>
</section>
<a href="#" id="trigger">Change</a>

的Javascript

<script type="text/javascript">
  var trigger = document.getElementById('trigger');
  var sectionToChange = document.getElementById('sectionToChange');
  trigger.onclick = function(e)
  {
       //toggle hover
       sectionToChange.className = (sectionToChange.className == 'activateHover') ? '' : 'activateHover';
       //restart animation
       if(sectionToChange.className != 'activateHover')
       {
         sectionToChange.className = 'activateHover';
       }
  }
</script>