gpt4 book ai didi

javascript - 在掷骰子事件监听器中,如何将警报延迟到新骰子图像加载之后?

转载 作者:行者123 更新时间:2023-11-28 17:07:02 25 4
gpt4 key购买 nike

我正在练习 javascript,并创建了一个带有两个骰子和数字 1-12 的小骰子掷骰子。掷骰子,与骰子总数相匹配的数字(1-12)会出现红色虚线边框,当您单击它时,它会变成灰色。

我的图像源是“die_1”到“die_6”,我只是随机生成一个数字1-6,然后将其放入“die_”字符串中以更改图像的src。

现在,如果您滚动的数字已经是灰色的,我会弹出一个警告,显示“再次滚动”。

我的问题是:在我当前的实现中,在骰子图像更改之前会弹出警报。一旦我单击“确定”,骰子就会更改以显示滚动的数字。有没有办法延迟警报,直到骰子的图像发生变化?

var diePicture1 = document.getElementById("die1");
var diePicture2 = document.getElementById("die2");
const NUMBERBUTTONS = document.querySelectorAll(".number-button");
buttonRoll = document.getElementById('roll');

/* Gets the values of the dice and adds them */

function totalDice(){
var die1Value = parseInt(diePicture1.src.substring(diePicture1.src.length - 5,diePicture1.src.length-4));

var die2Value = parseInt(diePicture2.src.substring(diePicture2.src.length - 5,diePicture1.src.length-4));

var result = die1Value + die2Value;

return result;

}

buttonRoll.addEventListener('click', function(){

/*Randomly generates two numbers 1-6
then changes the img src to match */


var dieNumber1 = Math.floor(Math.random()*6) +1;
var dieNumber2 = Math.floor(Math.random()*6) +1;
diePicture1.src = "die_" + dieNumber1 +".png";
diePicture2.src = "die_" + dieNumber2 +".png";
var total = totalDice();

/*Checks to see if there are any numbers leftover
with a red border. If so, clears them */

currentNumber = NUMBERBUTTONS[total-1];
for (i=0; i<12; i++) {
if (NUMBERBUTTONS[i].style.border = "2px dashed red"){
NUMBERBUTTONS[i].style.border = "";
}
}

/*Gives red border if the color is not gray already */


if (currentNumber.style.background != "gray") {
currentNumber.style.border = "2px dashed red";
} else {

/*this is what is popping up before the dice images have had a chance
to change on screen */

alert("Roll Again");
}

}, false);

/*Turns number gray when clicked on IF border is red */
document.addEventListener('click',function(e){
if (e.target.style.border === "2px dashed red"){
e.target.style.border = "";
e.target.style.background = "gray";
}


},false);

最佳答案

很简单。设置超时函数需要两个参数,您想要运行的内容以及您希望其运行的时间,因此为此将警报放入方法中并设置超时。

点击链接了解更多详情 https://www.w3schools.com/js/js_timing.asp

关于javascript - 在掷骰子事件监听器中,如何将警报延迟到新骰子图像加载之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55599649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com