繁体   English   中英

当我将鼠标悬停在文本上时,它会改变颜色并且颜色保持不变,我该如何做到这一点?

[英]How do I make it so when I hover over my text it changes color and the color stays changed?

我是 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 的情况下这是否可能。

你应该使用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>

将此添加到 css 但

p.black {
  color: black;
}

您需要为此使用 javascript

document.querySelector(".main").addEventListener("mouseover", function(e) {
   this.classList.add("black");
})

 .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% 也将颜色设置为黑色。

使用如下过渡技巧:

 .main { color: white; font-size: 20px; transition: color 9999s; /* super big value here */ } .main:hover { transition: color 1s cubic-bezier(0.165, 0.84, 0.44, 1); color: #000; }
 <p class=main> Lorem ipsum dolor sit amet </p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM