以下是一个实现随机循环单词并且可以暂停、自定义词库的微信小程序代码。

首先,在小程序的json配置文件中添加以下代码:

{
  "pages": [
    "index"
  ],
  "window": {
    "navigationBarTitleText": "随机单词"
  }
}

然后,在小程序的wxml文件中添加以下代码:

<view class='container'>
  <view class='word'>{{currentWord}}</view>
  <button class='start-btn' bindtap='start'>开始</button>
  <button class='pause-btn' bindtap='pause'>暂停</button>
  <button class='reset-btn' bindtap='reset'>重置</button>
  <button class='customize-btn' bindtap='customize'>自定义词库</button>
</view>

在小程序的wxss文件中添加以下代码:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.word {
  font-size: 40rpx;
  margin-bottom: 20rpx;
}

.start-btn,
.pause-btn,
.reset-btn,
.customize-btn {
  margin-top: 20rpx;
  font-size: 30rpx;
  padding: 10rpx 20rpx;
  border: 1rpx solid #999;
  border-radius: 5rpx;
}

.start-btn {
  background-color: #00CC66;
  color: #fff;
}

.pause-btn {
  background-color: #FF9900;
  color: #fff;
}

.reset-btn {
  background-color: #FF6666;
  color: #fff;
}

.customize-btn {
  background-color: #999;
  color: #fff;
}

最后,在小程序的js文件中添加以下代码:

Page({
  data: {
    words: ['apple', 'banana', 'cherry', 'durian', 'elderberry'], // 默认词库
    currentWord: '',
    intervalId: null,
    isPaused: true,
    currentIndex: 0
  },

  onLoad: function () {
    this.setData({
      currentWord: this.data.words[this.data.currentIndex]
    })
  },

  start: function () {
    if (this.data.isPaused) {
      this.setData({
        isPaused: false
      })
      this.data.intervalId = setInterval(() => {
        this.setData({
          currentIndex: (this.data.currentIndex + 1) % this.data.words.length,
          currentWord: this.data.words[(this.data.currentIndex + 1) % this.data.words.length]
        })
      }, 1000)
    }
  },

  pause: function () {
    clearInterval(this.data.intervalId)
    this.setData({
      isPaused: true
    })
  },

  reset: function () {
    clearInterval(this.data.intervalId)
    this.setData({
      isPaused: true,
      currentIndex: 0,
      currentWord: this.data.words[0]
    })
  },

  customize: function () {
    wx.navigateTo({
      url: '/pages/customize/customize',
    })
  }
})

这里的代码实现了以下功能:

  1. 在页面加载时,显示默认词库中的第一个单词。
  2. 点击“开始”按钮后,每秒钟随机循环显示词库中的单词。
  3. 点击“暂停”按钮后,停止随机循环。
  4. 点击“重置”按钮后,停止随机循环并显示词库中的第一个单词。
  5. 点击“自定义词库”按钮后,跳转到自定义词库页面。

如果要实现自定义词库的功能,可以在小程序中创建一个新页面,例如命名为customize。在该页面中,可以添加一个输入框,让用户输入单词,并将输入的单词保存到小程序的缓存中。然后,在随机循环单词的页面中,可以在onLoad生命周期函数中读取缓存中保存的自定义词库。具体实现方法可以参考微信小程序官方文档。

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

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

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