猿问

如何在悬停和单击时切换 HTML/CSS 动画

每当我将鼠标悬停在元素上或单击时,我都无法尝试停止和启动动画。这是我的 HTML 元素:


<div class='marquee'>

   <h1>Some Text</h1>

</div>

CSS:


.marquee {

    width: 80%;

    white-space: nowrap;

    overflow: hidden;

    box-sizing: border-box;

}


.marquee h1 {

    display: inline-block;

    padding-left: 100%;

    animation: marquee 15s linear infinite;

}


@keyframes marquee {

    0%   { transform: translate(0, 0); }

    100% { transform: translate(-100%, 0); }

}

现在,动画默认情况下会永远持续下去。我怎样才能拥有它,以便每当我将鼠标悬停在或单击时,动画就会相应地暂停和恢复。我假设在单击时暂停/重新启动动画,我需要一个 JavaScript 函数。任何帮助表示赞赏。h1div


偶然的你
浏览 96回答 2
2回答

HUWWW

您可以使用animation-play-state规则:.marquee {&nbsp; &nbsp; width: 80%;&nbsp; &nbsp; white-space: nowrap;&nbsp; &nbsp; overflow: hidden;&nbsp; &nbsp; box-sizing: border-box;}.marquee h1 {&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; padding-left: 100%;&nbsp; &nbsp; animation: marquee 15s linear infinite;}.marquee h1:hover {&nbsp; &nbsp; animation-play-state: paused;}@keyframes marquee {&nbsp; &nbsp; 0%&nbsp; &nbsp;{ transform: translate(0, 0); }&nbsp; &nbsp; 100% { transform: translate(-100%, 0); }}<div class='marquee'>&nbsp; &nbsp;<h1>Some Text</h1></div>或者用JS:function stopAnimation(e){&nbsp; &nbsp;if (e.target.style.animationPlayState == ""){&nbsp; &nbsp; &nbsp;e.target.style.animationPlayState = "paused";&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp;e.target.style.animationPlayState = "";&nbsp; &nbsp;}}.marquee {&nbsp; &nbsp; width: 80%;&nbsp; &nbsp; white-space: nowrap;&nbsp; &nbsp; overflow: hidden;&nbsp; &nbsp; box-sizing: border-box;}.marquee h1 {&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; padding-left: 100%;&nbsp; &nbsp; animation: marquee 15s linear infinite;}@keyframes marquee {&nbsp; &nbsp; 0%&nbsp; &nbsp;{ transform: translate(0, 0); }&nbsp; &nbsp; 100% { transform: translate(-100%, 0); }}<div class='marquee'>&nbsp; &nbsp;<h1 onclick="stopAnimation(event)">Some Text</h1></div>

Cats萌萌

我建议使用 jquery 来更改动画属性。$('.marquee').mouseenter(()&nbsp;=>&nbsp;{&nbsp;$(this).css("animation:&nbsp;marquee&nbsp;15s&nbsp;linear&nbsp;infinite");&nbsp;}&nbsp;); $('.marquee').mouseleave(()&nbsp;=>&nbsp;{&nbsp;$(this).css("animation:&nbsp;none");&nbsp;}&nbsp;);
随时随地看视频慕课网APP

相关分类

Html5
我要回答