javascript - How do I make it so when I hover over my text it changes color and the color stays changed?
问题描述
I'm new to web development and I just can't seem to figure out how to change the color of my text when hovered and make it stay changed. Currently I have this:
.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>
I understand why the color doesn't stay black after unhovered but I still don't know how to approach this. I'm not even sure if this is even possible without 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>
推荐阅读
- batch-file - 通过 .bat (cmd) 从应用程序创建 txt 文件的问题 - 未使用空格和逗号设置文本
- html - 使用 div 创建过滤器表
- c++ - C++ 存储到文件
- python - 如何在python中将离散数据转换为区间?
- active-directory - 添加 Redmine 用户失败(电子邮件已在使用中),但没有用户使用该电子邮件
- command-line - 从 TeamCity 覆盖 nuspec 变量
- makefile - 如何在makefile的自动变量后附加后缀?
- python - 使用判别函数的多类分类
- c# - 如果我在数据网格中进行任何更改,然后想将该详细信息显示到另一个数据网格
- mongodb - 使用聚合检查数组中是否存在值