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

标签 javascript css event-handling addeventlistener

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

相关文章:

javascript - 从回调和内联自调用函数访问父函数变量

javascript - 我怎样才能修复这个 jQuery 故障,使 div 在使用 .hover() 时不会试图消失?

html - CSS - 将图像保留在桌面框架图像中的响应式设计

python - 当小部件失去焦点时如何拦截

javascript - 在 google api 中设置用于绘制多边形的缩放选项

javascript - 使用正则表达式替换字符串引用 JavaScript 中的嵌套组

javascript - 用于 JavaScript 的 UML?

php - Ajax 实时文本框按下所有 Html 元素

spring - 在 Spring 中使用 @Async 的 @EventListener

javascript - 渲染 displaySIngleElement 组件 onClick react