我刚接触web开发,似乎不知道如何在悬停时更改文本的颜色,并使其保持不变。目前,我有以下内容:
.main{
color: white;
font-size: 20px;
}
.main:hover{
animation: textchange 1s cubic-bezier(0.165, 0.84, 0.44, 1);
}
@keyframes textchange{
from{
color: white;
}
to {
color:black;
}
}
<p class=main>
Lorem ipsum dolor sit amet
</p>
我理解为什么取消悬停后颜色不会保持黑色,但我仍然不知道如何处理这个问题。如果没有javascript,我甚至不确定这是否可能。
发布于 2021-10-24 08:55:31
您应该使用animation-fill-mode: forwards;
function enter() {
const main = document.getElementById('main-with-javascript');
main.style.animation = 'textchange 4s cubic-bezier(0.165, 0.84, 0.44, 1)';
main.style.animationFillMode = 'forwards';
}
function leave() {
const main = document.getElementById('main-with-javascript');
main.style.animation = 'textchangeReverse 4s cubic-bezier(0.165, 0.84, 0.44, 1)';
}
#main-with-javascript {
color: #dddddd;
font-size: 20px;
}
.main {
color: #dddddd;
font-size: 20px;
animation: textchangeReverse 4s cubic-bezier(0.165, 0.84, 0.44, 1);
animation-fill-mode: forwards;
}
.main:hover {
animation: textchange 4s cubic-bezier(0.165, 0.84, 0.44, 1);
/*Let the element retain the style values from the last keyframe when the animation ends*/
animation-fill-mode: forwards;
}
@keyframes textchange {
from {
color: #dddddd;
}
to {
color: black;
}
}
@keyframes textchangeReverse {
from {
color: black;
}
to {
color: #dddddd;
}
}
<h2>with css</h2>
<p class='main'>
Lorem ipsum dolor sit amet
</p>
<hr/>
<h2>with css and javasctipt</h2>
<p id='main-with-javascript' onmouseenter='enter()' onmouseleave='leave()'>
Lorem ipsum dolor sit amet
</p>
发布于 2021-10-24 08:23:21
将其添加到css,但是
p.black {
color: black;
}
为此,您需要使用javascript
document.querySelector(".main").addEventListener("mouseover", function(e) {
this.classList.add("black");
})
发布于 2021-10-24 08:52:16
.main{
color: rgb(206, 37, 37);
font-size: 20px;
}
.main:hover{
animation-name: textchange;
animation-duration: 1s;
animation-iteration-count: infinite;
}
@keyframes textchange{
0%{
color: rgb(0, 0, 0);
}
100%{
color:black;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="github.css">
</head>
<body>
<main>
<p class=main>
Lorem ipsum dolor sit amet
</p>
</main>
</body>
</html>
你需要将动画迭代次数设置为无限大,在关键帧内设置为0%,将颜色设置为黑色,对于100%,也将颜色设置为黑色。
https://stackoverflow.com/questions/69694972
复制相似问题