我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!
功能介绍
一组9个单词,点击一个单词板,单词板翻转,显示中文翻译,再次点击单词板翻转回去显示英文,点击【再来一组】,随机生成新的9个单词。
只需更改代码中的words变量,即可更换想要背诵的单词。
涉及知识点
css旋转(transform),css过渡(transition),一些js
代码块
代码说明
- words变量:保存了需要背诵的单词
- filterWords:保存了words,每次背完后的单词会被删除
- 使用document.createElement('div')生成单词框,即包含9个单词的容器
let ul = document.createElement('div')
ul.className = 'word_ul'
ul.id = 'word'
document.getElementById('wrap').appendChild(ul)
- 通过for循环生成9个单词,通过Math.random()生成随机的rgb作为每个单词板的背景颜色,一个li表示一个单词板,一个单词板中有一个li1,一个li2,一开始li1显示,li2隐藏并且是旋转180度的状态,li1的内容是单词的英文,li2的内容是单词的中文。
然后给li添加点击事件,如果原本是li1显示li2隐藏的,即转变为li2显示li1隐藏,并且将li旋转180度。
for (let i = 0; i < 9; i++) {
if (filterWords.length > 0) {
let index = parseInt(Math.random() * filterWords.length)
let word = filterWords.splice(index, 1)
let li = document.createElement('div')
li.className = 'word_li'
let random1 = parseInt(Math.random() * 220)
let random2 = parseInt(Math.random() * 220)
let random3 = parseInt(Math.random() * 220)
li.style.background = `rgb(${random1}, ${random2}, ${random3})`
let li1 = document.createElement('div')
li1.className = 'word_li1'
li1.style.display = 'block'
let li2 = document.createElement('div')
li2.className = 'word_li2'
li2.style.display = 'none'
li2.style.transform = 'rotateY(180deg)'
li1.innerText = word[0].en
li2.innerText = word[0].zh
li.appendChild(li1)
li.appendChild(li2)
li.onclick = function () {
if (li1.style.display === 'block') {
this.style.transform = 'rotateY(180deg)'
setTimeout(() => {
li1.style.display = 'none'
li2.style.display = 'block'
}, 500)
} else {
this.style.transform = 'rotateY(0)'
setTimeout(() => {
li1.style.display = 'block'
li2.style.display = 'none'
}, 500)
}
}
ul.appendChild(li)
}
}
- 判断filterWords的长度,如果为0说明所有单词都被抽取完,结束背诵
if (filterWords.length === 0) {
ul.innerText = '已抽取完所有单词!'
ul.style.padding='10px'
return
}
- 【再来一组】点击事件,点击后移除ul元素,重新生成9个单词。
document.getElementById('Button').onclick = function () {
let ul = document.getElementById('word')
if (ul) {
document.getElementById('wrap').removeChild(ul)
}
initWords()
}
写在最后
以上就是所有代码的解释,如有帮助请点赞哟~