【发布时间】:2022-01-07 22:59:01
【问题描述】:
我想实现以下内容:动画应该只在我将鼠标悬停在 div 上时开始。将鼠标悬停在 div 上后,结束编号应该保持可见,并且不会更改为开始值。
这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animation</title>
<style>
.counter{
color: white;
font-size: 100px;
height: 300px;
width: 400px;
background-color: black;
display: flex;
align-items:center;
justify-content: center;
}
.animate{
position:absolute;
opacity:0;
transition:0s 180s;
}
.animate:hover {
opacity:1;
transition:0s;
}
</style>
</head>
<body>
<div id="animate" style="background-color: orange; width: 300px; height: 200px;" class="counter" data-target="500">0</div>
<script>
const counters = document.querySelectorAll('.counter');
for(let n of counters) {
const updateCount = () => {
const target = + n.getAttribute('data-target');
const count = + n.innerText;
const speed = 5000; // change animation speed here
const inc = target / speed;
if(count < target) {
n.innerText = Math.ceil(count + inc);
setTimeout(updateCount, 1);
} else {
n.innerText = target;
}
}
updateCount();
}
</script>
</body>
</html>
【问题讨论】:
-
尝试在鼠标悬停事件发生时在元素上启动动画,而不是将它们全部设置为从一开始就开始动画。
-
我已经修改了我的问题...如何实现鼠标悬停事件?