gpt4 book ai didi

javascript - 通过添加一个类来为文本元素设置动画,并通过删除该类将其设置回初始颜色

转载 作者:行者123 更新时间:2023-12-01 15:59:17 25 4
gpt4 key购买 nike

如果出于某种原因我不想给我的元素颜色类(我只是给它一个类名以便能够选择它但我希望颜色类不附加到元素)

如何在颜色之间切换?我的意思是将颜色从蓝色变为红色,然后再将颜色从红色变为蓝色......

我这里有一个丑陋的解决方案,但我认为应该有更好、更简洁的方法,比如使用纯 CSS,比如切换类,当类被附加时,如果它删除元素动画回红色,元素是蓝色的。 ..

const text = document.querySelector(".myClass");

text.addEventListener("click", function (){

if(text.classList.contains("changeBlue")){
text.classList.add("changeRed");
text.classList.remove("changeBlue");
} else if(text.classList.contains("changeRed")){
text.classList.add("changeBlue");
text.classList.remove("changeRed");
} else {
text.classList.add("changeRed");
}


})
@keyframes changeRedAnime {
from {color: blue}
to {color: red}
}

.changeRed {
animation-name: changeRedAnime;
animation-duration: .5s;
animation-fill-mode: forwards;
}

@keyframes changeBlueAnime {
from {color: red}
to {color: blue}
}

.changeBlue {
animation-name: changeBlueAnime;
animation-duration: .5s;
animation-fill-mode: forwards;
}

.myClass {
user-select:none;
color:blue;
cursor:pointer;
}
<div class="myClass">This is a sample text.</div>

最佳答案

一种替代方法是将 css 类名存储在数组中并使用一些 index-access-increment-modulo 魔法

示例

const text = document.querySelector(".myClass");
const classList = text.classList;
const values = ["changeBlue", "changeRed"]
let it = 0;

text.addEventListener("click", function () {
classList.remove(values[it++ % 2]);
classList.add(values[it % 2]);
})
@keyframes changeRedAnime {
from {color: blue}
to {color: red}
}

.changeRed {
animation-name: changeRedAnime;
animation-duration: .5s;
animation-fill-mode: forwards;
}

@keyframes changeBlueAnime {
from {color: red}
to {color: blue}
}

.changeBlue {
animation-name: changeBlueAnime;
animation-duration: .5s;
animation-fill-mode: forwards;
}

.myClass {
user-select:none;
color:blue;
cursor:pointer;
}
<div class="myClass">This is a sample text.</div>

关于javascript - 通过添加一个类来为文本元素设置动画,并通过删除该类将其设置回初始颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62365377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com