每次点击时我都无法更改元素的宽度。 现在,每次运行该功能时,宽度都会增加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">
我可以更改或添加哪些功能,以便我自定义增量百分比?
提前谢谢!
答案 0 :(得分:1)
更好地理解问题后:
尝试将显示与游戏逻辑分开,此时您正在将游戏状态保存在html元素中,这并不理想。像这样:
// Place this somewhere where it's accessible to you other game logic.
var INCREASE = 5;
var gameState = {
progress: 1,
}
// Update the actual game state.
function updateProgress(clickElement, gameState) {
gameState.progress *= INCREASE;
displayProgress(clickElement, gameState.progress);
}
// displayProgress now only displays, it is not used to store the progress.
function displayProgress(clickElement, progress){
document.getElementById(clickElement).onclick = function(){
var progress = document.getElementById("progress");
currentWidth.innerHTML = "Progress: " + progress + "%";
progress.style.width = parseInt(progress) + "%";
}
}
从设计角度来看,这更有意义。
答案 1 :(得分:1)
(没看到你的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>