如何在鼠标移出时保持悬停状态?
How do I maintain the state of a hover on mouse out?
我正在尝试将一条线变成一个长矩形的过渡。我想让它在转换完成时,即使鼠标没有悬停在其上,最终状态也会保持不变。
这是我当前的代码:
#line {
width: 300px;
height: 1px;
background-color: darkblue;
transition: height 2s;
-webkit-transition: height 2s;
}
#line:hover {
width: 300px;
height: 200px;
background-color: darkblue;
}
<div id="line"></div>
我认为最好的解决方案是添加一个添加 class 的小脚本。 class 取消悬停后仍然存在:
window.addEventListener('DOMContentLoaded', function() {
document.getElementById('line').addEventListener('mouseover', function(event) {
document.getElementById('line').classList.add('activated');
});
});
#line {
width: 300px;
height: 1px;
background-color: darkblue;
transition: height 2s;
-webkit-transition: height 2s;
}
#line.activated{
width: 300px;
height: 200px;
background-color: darkblue;
}
<body>
<div id="line"></div>
</body>
仅通过 CSS 获得此效果的一种棘手方法:将元素上的过渡延迟设置为一个巨大的值。并在悬停状态下将其设置为 0
悬停时,元素会变为悬停状态,这种转换是即时的。
当您取消悬停时,在它开始之前会有 9999 秒的延迟(好吧,并不是真的 永远,但没有人会注意到)
#line {
width: 300px;
height: 10px;
background-color: darkblue;
-webkit-transition: height 1s 9999s;
transition: height 1s 9999s;
}
#line:hover{
width: 300px;
height: 200px;
background-color: darkblue;
-webkit-transition-delay: 0s;
transition-delay: 0s;
}
<body>
<div id="line"></div>
</body>
我正在尝试将一条线变成一个长矩形的过渡。我想让它在转换完成时,即使鼠标没有悬停在其上,最终状态也会保持不变。
这是我当前的代码:
#line {
width: 300px;
height: 1px;
background-color: darkblue;
transition: height 2s;
-webkit-transition: height 2s;
}
#line:hover {
width: 300px;
height: 200px;
background-color: darkblue;
}
<div id="line"></div>
我认为最好的解决方案是添加一个添加 class 的小脚本。 class 取消悬停后仍然存在:
window.addEventListener('DOMContentLoaded', function() {
document.getElementById('line').addEventListener('mouseover', function(event) {
document.getElementById('line').classList.add('activated');
});
});
#line {
width: 300px;
height: 1px;
background-color: darkblue;
transition: height 2s;
-webkit-transition: height 2s;
}
#line.activated{
width: 300px;
height: 200px;
background-color: darkblue;
}
<body>
<div id="line"></div>
</body>
仅通过 CSS 获得此效果的一种棘手方法:将元素上的过渡延迟设置为一个巨大的值。并在悬停状态下将其设置为 0
悬停时,元素会变为悬停状态,这种转换是即时的。
当您取消悬停时,在它开始之前会有 9999 秒的延迟(好吧,并不是真的 永远,但没有人会注意到)
#line {
width: 300px;
height: 10px;
background-color: darkblue;
-webkit-transition: height 1s 9999s;
transition: height 1s 9999s;
}
#line:hover{
width: 300px;
height: 200px;
background-color: darkblue;
-webkit-transition-delay: 0s;
transition-delay: 0s;
}
<body>
<div id="line"></div>
</body>