亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在懸停和單擊時切換 HTML/CSS 動畫

如何在懸停和單擊時切換 HTML/CSS 動畫

偶然的你 2023-10-30 20:28:01
每當我將鼠標懸停在元素上或單擊時,我都無法嘗試停止和啟動動畫。這是我的 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
查看完整描述

2 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

您可以使用animation-play-state規則:


.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;

}


.marquee h1:hover {

    animation-play-state: paused;

}


@keyframes marquee {

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

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

}

<div class='marquee'>

   <h1>Some Text</h1>

</div>

或者用JS:


function stopAnimation(e){

   if (e.target.style.animationPlayState == ""){

     e.target.style.animationPlayState = "paused";

   } else {

     e.target.style.animationPlayState = "";

   }

}

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

}

<div class='marquee'>

   <h1 onclick="stopAnimation(event)">Some Text</h1>

</div>


查看完整回答
反對 回復 2023-10-30
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

我建議使用 jquery 來更改動畫屬性。

$('.marquee').mouseenter(() => { $(this).css("animation: marquee 15s linear infinite"); } );

$('.marquee').mouseleave(() => { $(this).css("animation: none"); } );



查看完整回答
反對 回復 2023-10-30
  • 2 回答
  • 0 關注
  • 133 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號