如何停止css动画在当前位置悬停

How to stop css animation in current position on hover?

本文关键字:位置 悬停 何停止 css 动画      更新时间:2023-09-26

我有一个div里面移动另一个div。当我悬停在.container上时,我需要在当前位置停止.block。怎么做呢?

HTML:

<div class="container">
    <div class="block"></div>
</div>
CSS:

.container {
    width: 200px;
    height: 100px;
    padding: 10px;
    border: 1px solid #000;
    position: relative;
}
.block {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    animation: move 2s linear infinite;
}
@keyframes move {
    0% { left: 10px; }
    25% { left: 50px; }
    50% { left: 100px; }
    75% { left: 50px; }
    100% { left: 10px; }
}
演示

可以添加

.block:hover
{
    animation-play-state: paused;
}

将鼠标悬停在动画上时暂停动画。

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state

当鼠标悬停在.container上时可以暂停动画。考虑以下css:

.container:hover .block{
    animation-play-state: paused;
}

CSS:

.container:hover > .block {
    -webkit-animation-play-state:paused;
    -moz-animation-play-state:paused;
    -o-animation-play-state:paused; 
    animation-play-state:paused;
}

JS:

var node = document.getElementsByClassName("block")[0];
node.addEventListener('mouseenter', function(evt) {
    evt.currentTarget.style.webkitAnimationPlayState = 'paused';    
});
node.addEventListener('mouseleave', function(evt) {
    evt.target.style.webkitAnimationPlayState = 'running';  
});