【发布时间】:2019-11-11 07:12:45
【问题描述】:
尝试以不同的颜色闪烁 div,它们之间有一段时间(不使用 jquery)。该程序在调试器中运行良好,但在运行时,所有更改都发生得太快,用户看不到任何东西。
尝试使用 setTimeout 无济于事(可能没有正确使用)
function makeBoard() {
var squareNum = 4
var selected
container = document.createElement('div')
container.id = 'container'
document.body.appendChild(container);
for (let index = 0; index < squareNum; index++) {
squareDiv = document.createElement('div')
squareDiv.className = 'square'
squareDiv.id = '' + (index + 1)
container.appendChild(squareDiv)
}
selected = document.getElementById('1')
selected.classList.add('selected')
return selected
}
function dimSwitch() {
var turnCnt = 1
var posIndex = 0
var selectedDivs = []
var tempCnt = 0
var tempIndex = 0
var timeNum = getMaxPos()
while (tempCnt < timeNum) {
var posIndex = posArr.indexOf(turnCnt, tempIndex)
tempIndex = posIndex + 1
while (posIndex !== -1) {
selectedDivs.push(document.getElementById(posIndex + 1 + ''))
posIndex = posArr.indexOf(turnCnt, tempIndex)
tempIndex = posIndex + 1
}
selectDiv(selectedDivs) //After this i would like a small delay
turnCnt++
tempCnt++
for (let index = 0; index < selectedDivs.length; index++) {
selectedDivs[index].classList.remove('selected')
}
selectedDivs = []
}
}
function drawMove(currDiv, direction) {
var nextDiv
currDiv.classList.remove('selected')
nextDiv = document.getElementById((parseInt(currDiv.id) + direction))
nextDiv.classList.add('selected')
return nextDiv
}
function selectDiv(divs) {
for (let index = 0; index < divs.length; index++) {
divs[index].classList.add('selected')
}
}
function getMaxPos() {
var maxNum = 0
for (let index = 0; index < posArr.length; index++) {
if (posArr[index] > maxNum) maxNum = posArr[index]
}
return maxNum
}
var TurnNum = 4 //Number of turns
var posArr = [1]
var turnCnt = 1
var currDiv = makeBoard()
document.onkeydown = function (event) {
switch (event.keyCode) {
case 37:
//Left Key -1
posArr[turnCnt] = posArr[turnCnt - 1] - 1
currDiv = drawMove(currDiv, -1)
turnCnt++
break;
case 39:
//Right key +1
posArr[turnCnt] = posArr[turnCnt - 1] + 1
currDiv = drawMove(currDiv, 1)
turnCnt++
break;
case 40:
currDiv.classList.remove('selected')
dimSwitch()
break;
}
if (turnCnt === TurnNum) {
currDiv.classList.remove('selected')
dimSwitch()
}
};
函数 selectDivs 应该在每次执行之间运行一段时间 每当使用延迟或超时时,它都会冻结或正常工作 在我删除 for 循环中的类之前,用户应该能够看到哪些 div 为红色(“选定”类)。
这就是我尝试使用 setTimeout 的方式,但其余代码一直在后台运行,而我看到的所有 div 都是红色的:
setTimeout(function(){
for (let index = 0; index < selectedDivs.length; index++) {
selectedDivs[index].classList.remove('selected')
}
},1000)
【问题讨论】:
-
显然这段代码会立即运行。你是怎么用 setTimeout 没用的?
-
setTimeout(function(){ for (let index = 0; index
-
请发布一个最小的工作示例(或者在这种情况下不工作),包括HTML(和任何重要的东西),所以人们不要重建你的案子并不难。这样就可以更轻松、更快捷地提出解决方案。
标签: javascript html settimeout delay