如何使 CSS3 悬停过渡只运行一次,而不是在用户“取消悬停"后“倒带"?

人气:1,051 发布:2022-09-11 标签: css animation hover

问题描述

我有一些 CSS(见下文),当用户将鼠标悬停在外部字段上时,我想使内部 div(小猫)在屏幕上平移.这工作正常,但正如您所料,当用户从外场移开他或她的鼠标时,动画会倒带",然后(当然)如果用户再次悬停,它会重播.我试图弄清楚如何让这个动画运行一次(用户第一次悬停在外场上),然后不再倒带或再次播放,无论他或她将来悬停在什么上面.这可能吗?我不想在我的页面上添加另一个脚本,但如果这是唯一的解决方法,那么我愿意接受.提前致谢!

I have some CSS (see below) and I want to cause the inner div (kitty) to translate across the screen when the user hovers over the outer field. This is working fine but, as you would expect, when the user removes his or her mouse from the outer field, the animation 'rewinds' and then (of course) it replays if the user hovers again. I am trying to figure out how to get this animation to run once (the first time the user hovers over the outer field) and then not rewind or play ever again, no matter what he or she hovers over in future. Is this possible? I'd prefer not to add another script to my page, but if that is the only fix then I'm open to it. Thanks in advance!

<style type="text/css">
div.kitty {
    position: absolute; 
    bottom: 50px; 
    left: 20px; 
    -webkit-transition: all 3s ease-in; 
    -moz-transition: all 3s ease-in; 
    -o-transition: all 3s ease-in; 
    -ms-transition: all 3s ease-in;
    animation-iteration-count: 1;
}
#actioner {
    padding: 0px;
    height: 400px;
    position: relative;
    border-width: 1px;
    border-style: solid;
}
#actioner:hover div.kitty{
    -webkit-transform: translate(540px,0px); 
    -moz-transform: translate(540px,0px); 
    -o-transform: translate(540px,0px); 
    -ms-transform: translate(540px,0px);
}
</style>

<div id="actioner">
    <div class="kitty">Kitty-Cat Sprite</div>
</div>

推荐答案

恕我直言,纯 CSS 是不可能的.最简单的解决方案是使用 jQuery.

IMHO, it is not possible to do with pure CSS. The easiest solution will be using jQuery.

// css
.actioner{
    -webkit-transform: translate(540px,0px); 
    -moz-transform: translate(540px,0px); 
    -o-transform: translate(540px,0px); 
    -ms-transform: translate(540px,0px);
}

// script
$(function(){
    $('.kitty').one("mouseover", function() {
        $('.kitty').addClass('actioner');
    });
});

277