Jquery 在按钮点击时用进度条做计时器

Jquery on button click do timer with progress-bar

所以我试图制作一个小游戏,但第一步就是行不通。 这是我的代码

<div id="box1">
        <button id="button">Click Me</button>
        <div id="progress-bar"></div>
    </div>

$('button').click(function() {
var progressBar = $('#progress-bar'),
width = 0;
progressBar.width(width);
var interval = setInterval(function () {
    width += 2.5;
    progressBar.css('width', width + '%');
    if (width >= 100) {
        clearInterval(interval);
    }
 }, 125)
});

#progress-bar {
width: 0;
background: red;
text-align: center;
overflow: hidden;   
height: 4px;
position: absolute;
bottom: 0px;
}
#box1 {
height: 100px;
width: 600px;
position: relative;
border: 1px solid grey;
}

所以当点击按钮时,box1 的底部会出现一个进度条。 准备文档时它可以工作,但使用 .click 时它不起作用。

准备好文档时它可以工作,但使用 .click 时它不起作用。

当你有一个 $(document).ready 包裹你的代码时它会起作用,因为它指示 javascript 引擎等待所有 js 完全加载后再尝试执行。

如果您没有 $(document).ready 并且在加载所有内容之前单击,则会出现控制台错误。

按 F12 打开开发人员工具并执行相同的操作,我怀疑您会在控制台中看到错误。