微信小程序随机单词循环器:自定义词库、暂停功能

这是一个简单的微信小程序代码,可以随机循环显示单词,并提供暂停功能,用户还可以自定义词库内容。

一、小程序界面

<!--index.wxml-->
<view class='container'>
  <view class='word'>{{currentWord}}</view>
  <button class='btn' bindtap='toggle'>{{isPlaying ? '暂停' : '开始'}}</button>
  <button class='btn' bindtap='addWord'>添加词汇</button>
</view>

小程序界面包含三个部分:

  • 显示区域: 显示当前的随机单词,由 currentWord 变量控制。
  • 开始/暂停按钮: 点击按钮可切换开始和暂停状态,由 isPlaying 变量控制。
  • 添加词汇按钮: 点击按钮可添加自定义单词到词库。

二、小程序代码

//index.js
const words = ['hello', 'world', 'apple', 'banana', 'orange']; //默认词库
let timer = null; //定时器ID

Page({
  data: {
    currentWord: '',
    isPlaying: false
  },
  onLoad: function () {
    this.reset();
  },
  toggle: function () {
    if (this.data.isPlaying) {
      clearInterval(timer);
    } else {
      this.play();
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  play: function () {
    timer = setInterval(() => {
      const index = Math.floor(Math.random() * words.length);
      this.setData({
        currentWord: words[index]
      })
    }, 1000);
  },
  reset: function () {
    clearInterval(timer);
    this.setData({
      currentWord: '',
      isPlaying: false
    })
  },
  addWord: function () {
    wx.showModal({
      title: '添加词汇',
      content: '请输入一个新词汇',
      success: (res) => {
        if (res.confirm) {
          const newWord = res.inputValue;
          words.push(newWord);
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          })
        }
      }
    })
  }
})

代码主要功能如下:

  • 默认词库: words 数组存储默认词库内容。
  • 定时器: timer 变量用于存储定时器 ID。
  • 页面加载: onLoad 方法初始化页面,调用 reset 方法重置状态。
  • 开始/暂停: toggle 方法控制开始和暂停状态,使用 setInterval 和 clearInterval 操作定时器。
  • 随机显示: play 方法使用 setInterval 函数每秒随机选择一个单词并更新页面。
  • 重置状态: reset 方法清除定时器并重置页面状态。
  • 添加词汇: addWord 方法使用 wx.showModal 弹出模态框,让用户输入新的单词并添加到词库。

三、总结

本小程序代码简单易懂,功能完善,可以帮助用户快速搭建一个随机循环单词的小程序,并提供自定义词库功能,方便学习或娱乐使用。

微信小程序随机单词循环器:自定义词库、暂停功能

原文地址: https://www.cveoy.top/t/topic/nWqK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录