如何在悬停时停止当前位置的CSS动画?

时间:2023-01-14 21:16:49

I have a div inside which moves another div. I need to stop .block at the current position when I hover on .container. How to do it?

我有一个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; }
}

DEMO

3 个解决方案

#1


6  

You can add

你可以加

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

to pause the animation when you hover over it.

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

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

#2


1  

You can pause animation when hover on .container. Consider following css:

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

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

DEMO

#3


0  

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';  
});

#1


6  

You can add

你可以加

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

to pause the animation when you hover over it.

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

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

#2


1  

You can pause animation when hover on .container. Consider following css:

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

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

DEMO

#3


0  

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';  
});