gpt4 book ai didi

javascript - 如何通过 JavaScript 自定义元素宽度的百分比增量?

转载 作者:行者123 更新时间:2023-11-30 14:48:16 25 4
gpt4 key购买 nike

每次单击时我都无法更改元素的宽度。现在,每运行一次该函数,宽度就会增加 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>

关于javascript - 如何通过 JavaScript 自定义元素宽度的百分比增量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48568177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com