<!DOCTYPE html>
<html>
<head>
<title>数字化人才认证数动画</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/TextPlugin.min.js"></script> <style>
.counter {
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<span class="counter" data-target="12345">0</span>
<script>
$(document).ready(function() {
gsap.registerPlugin(TextPlugin); // 注册 TextPlugin 插件
$('.counter').each(function() {
const target = parseInt($(this).data('target'));
gsap.to($(this), {
duration: 1,
ease: "power2.out",
text: target,
onUpdate: function() {
$(this.target).text(Math.round($(this.target)._gsap.get(0)));
}
});
});
});
</script>
</body>
</html>
多个数字使用一个方法会从上到下加载。
报错:
Cannot read properties of undefined (reading ‘get’) at Tween.onUpdate [as _onUpdate] 。
onUpdate: function() {
// 这里的 this.target 是undefined
$(this.target).text(Math.round(this.target._gsap.get(0)));
}
解决方法:
onUpdate: function() {
$(this.target).text(Math.round($(this.target)._gsap.get(0)));
}