我是编程新手,但正在尝试解决问题。 当我按下“d”按钮时,我试图增加进度条。我正在尝试以递归方式执行此操作,但我没有足够的技能来正确执行此操作。任何帮助将不胜感激。
到目前为止,我的 js 文件看起来像这样:
window.addEventListener('keypress', function(e) {
function counter(p) {
//if the button is "d"
if (e.keyCode === 100) {
//target progressbar width and increase it
$('#progressbar').css('width', function(index, value) {
return $("#progressbar").css('width', ((p * 2) + "%"));
});
if ($('#progressbar').width() < 100) {
return counti(p + 1)
}
}
};
counti(1);
});
我的 html:
<div id = "myProgress" >
<div id = "progressbar" > 0 / 50 </div>
</div>
最佳答案
var count = 0;
var maxCount = 50;
var progressBar = document.getElementById("progressbar")
window.addEventListener("keypress", function(e) {
//if the button is "d"
if (e.keyCode === 100) {
// increase count if it's less than maxCount
count = count === maxCount ? maxCount : count + 1;
//target progressbar width and increase it
var newWidth = (count / maxCount) * 100 + "%";
progressBar.style.width = newWidth;
progressBar.innerHTML = count + "/" + maxCount
}
});
#myProgress {
width: 400px;
height: 30px;
background-color: #e4e4e4;
}
#progressbar {
width: 0%;
height: 30px;
background-color: #5980a7;
color: #fff;
}
<div id="myProgress">
<div id="progressbar">0/50</div>
</div>
关于javascript - 当我们按下按钮时,进度条会增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890497/