javascript - 进度条、最大值并重置为 100%

标签 javascript php html css sql

我在 sql 中处理连接到 XP 和 MAX XP 的进度条。每次单击按钮,您都会获得 1 xp,最大 xp 为 10。我希望当用户达到 100% XP 时,它应该重置回 0%。如果您知道如何使用该“重置”来增加在这种情况下的值,则用户的级别应该在 100% 重置时使其当前级别 + 1。

我通过此代码每次点击插入 1 xp:

$sql = "UPDATE progression SET xp=(xp + 1) WHERE username='$username' LIMIT 1";

我通过使 1 xp = to 10% of bar 从此代码创建 100% xp bar 值:

$percent = intval($resultprogression[0]['xp']*100/$resultprogression[0]['max xp']);

我用这段代码在 html/css 中输出:

<div class="experience-bar-container">
        <div id="value" style="width:<?php echo $percent ?>%;"></div>
        <h3>XP: <span><?php echo $percent ?>%</span></h3>
</div>


div#value {
   display: block;
   position: absolute;
   z-index: 2;
   height: 19%;
   background: red;
   left: 0;
 }

最佳答案

你必须使用 js。 解决方案:在进度 div 中添加一个数据属性来存储进度值:

<div class="experience-bar-container">
  <div id="value" data-value="<?php echo $percent ?>" style="width:<?php echo $percent ?>%;"></div>
  <h3>XP: <span id="xpPercent"><?php echo $percent ?>%</span></h3>
  <button class="xpButton" id="minus">-</button>
  <button class="xpButton" id="plus">+</button>
</div>

然后在使用数据属性值更新条宽的按钮上添加监听器:

var progress = document.getElementById("value");
var xpPercent = document.getElementById("xpPercent");

document.getElementById("minus").addEventListener("click", function() {
  var newValue = parseInt(progress.getAttribute('data-value')) - 10;
  update(newValue);
});
document.getElementById("plus").addEventListener("click", function() {
  var newValue = parseInt(progress.getAttribute('data-value')) + 10;
  update(newValue);
});

“update”函数检查进度,并在需要时调用调用 dbupdate 函数的重置函数

function update(newValue) {
  progress.style.width = newValue + '%';
  progress.setAttribute('data-value', newValue);
  xpPercent.innerText = newValue + '%';
  if (newValue === 100) {
    reset();
  }
}:

function reset() {
  progress.style.width = '0%';
  progress.setAttribute('data-value', 0);
  xpPercent.innerText = '0%';
  dbUpdate();
}

function dbUpdate() {
  // do Ajax stuff to update user's level
}

https://jsfiddle.net/qpg7t603/1/

如果您不打算支持 IE10,您应该查看进度标签:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Progress

关于javascript - 进度条、最大值并重置为 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47533154/

相关文章:

php - jQuery UI 可排序 php/mysql

javascript - 在表单提交时,它显示 - 此网页有一个重定向循环

javascript - 如何使用Javascript向html页面添加/删除CSS/颜色样式?

javascript - Angular 5 组件变量在单页应用程序中未定义,无需刷新浏览器

JavaScript 和 PHP : How to encode a normal string in a encoded short string?

javascript - 更改 CDN 托管的 JS 文件的设置,而不触及文件

javascript - jQuery 数据表 : comparing two columns

PHP 执行一条插入 SQL 但在数据库中添加两条记录

javascript - PHP 返回中的框

html - Nokogiri 从 html 中提取节点