当前位置:   article > 正文

微信小程序展示倒计时

微信小程序展示倒计时

html
 

  1. <view class="countdown">
  2. <text>倒计时:</text>
  3. <text wx:for="{{countdown}}" wx:key="index">{{item}}</text>
  4. </view>

ts
 

  1. data: {
  2. countdown: [], // 存放倒计时数组
  3. targetTime: '', // 目标时间戳
  4. intervalId: null, // 定时器ID
  5. }
  6. startCountdown () {
  7. const that = this;
  8. // 每秒更新一次倒计时
  9. this.data.intervalId = setInterval(function () {
  10. const now = new Date().getTime();
  11. const diff = that.data.targetTime - now;
  12. if (diff <= 0) {
  13. // 倒计时结束,清除定时器
  14. clearInterval(that.data.intervalId);
  15. that.setData({
  16. countdown: ['倒计时结束'],
  17. });
  18. } else {
  19. // 计算剩余的天、时、分、秒
  20. const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  21. const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  22. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  23. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  24. that.setData({
  25. countdown: [days, '天', hours, '时', minutes, '分', seconds, '秒'],
  26. });
  27. }
  28. }, 1000);
  29. },
  30. onLoad: function (options) {
  31. this.setData({
  32. targetTime: new Date('2024-04-28 16:53:10').getTime(),
  33. });
  34. this.startCountdown();
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/448558
推荐阅读
相关标签
  

闽ICP备14008679号