每隔1秒出现一个随机颜色的小方块点击消失 超过20个小方块提示失败
11太会写这个js的代码麻烦回答带个例子
1条回答 默认 最新
- 「已注销」 2023-03-08 10:14关注
“Devil组”引证GPT后的撰写:
以下是一个简单的实现你所描述的功能的 JavaScript 代码示例:HTML 代码:
<div id="container"></div> <div id="message"></div>
CSS 代码:
#container { position: relative; width: 300px; height: 300px; border: 1px solid black; } .box { position: absolute; width: 20px; height: 20px; background-color: red; cursor: pointer; } #message { font-size: 20px; font-weight: bold; color: red; text-align: center; }
JavaScript 代码:
const container = document.getElementById("container"); const message = document.getElementById("message"); let count = 0; const limit = 20; function createBox() { if (count >= limit) { message.textContent = "You failed!"; return; } const box = document.createElement("div"); box.classList.add("box"); box.style.top = Math.floor(Math.random() * (container.clientHeight - 20)) + "px"; box.style.left = Math.floor(Math.random() * (container.clientWidth - 20)) + "px"; box.style.backgroundColor = getRandomColor(); box.addEventListener("click", () => { container.removeChild(box); count++; }); container.appendChild(box); setTimeout(() => { container.removeChild(box); count++; }, 1000); } function getRandomColor() { return "#" + Math.floor(Math.random() * 16777215).toString(16); } setInterval(createBox, 1000);
这段代码将会在 container 元素中每秒钟创建一个随机颜色的小方块,点击小方块即可消失。当创建的小方块数量超过 limit 时,将会提示失败。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 求帮我调试一下freefem代码
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗
- ¥60 求一个简单的网页(标签-安全|关键词-上传)
- ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
- ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图