每次单击时都无法更改元素的宽度。
现在,每次运行该功能时,宽度都会增加1%。
我希望能够在函数中传递参数/参数,这将允许我自定义点击的百分比增量。
即使点击的百分比增加5,或者使点击的百分比增加10或25。
这是我到目前为止拥有的功能:
function progressBar(clickElement){
document.getElementById(clickElement).onclick = function(){
var progress = document.getElementById("progress");
var current_width = progress.style.width.replace("%", " ");
var currentWidth = document.getElementById("currentWidth");
current_width = (current_width > 100) ? 100 : current_width;
currentWidth.innerHTML = "Progress: " + current_width++ + "%";
progress.style.width = parseInt(current_width) + "%";
}
}
注意以下代码行:
var current_width = progress.style.width.replace("%", " ");
这是我的HTML:
<div id="container">
<div id="loader">
<div id="progress"></div>
</div>
<div id="currentWidth"></div>
<input id="increase" type="submit" value="Increase">
我可以更改或添加什么功能以自定义百分比增量?
先感谢您!
最佳答案
(没有看到你的HTML,所以我做了我自己的)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>click game</title>
</head>
<body>
<div id="info">Progress: 0%</div>
<div id="progress" style="width:0%;height:100px;border:1px solid black;"></div>
<button id="increase100">1 click needed</button>
<button id="increase20">5 clicks needed</button>
<button id="increase4">25 clicks needed</button>
<script type="text/javascript">
let info = document.getElementById("info");
let progress = document.getElementById("progress");
function makedynamic(button, neededclicks) {
let stepsize = 100 / neededclicks;
document.getElementById(button).onclick = function() {
let width = progress.style.width.replace("%", "");
width = parseInt(width) + stepsize;
if (width >= 100) {
progress.style.width = "100%";
info.innerHTML = stepsize > 10 ? "You made it!" : "ouch, my fingerrrrs";
} else {
width = width +"%";
progress.style.width = width;
info.innerHTML = "Progress: " + width;
}
}
}
makedynamic('increase100',1);
makedynamic('increase20',5);
makedynamic('increase4',25);
</script>
</body>
</html>