【问题标题】:Progress bar, max and reset on 100%进度条,最大值并重置为 100%
【发布时间】:2017-11-28 13:47:47
【问题描述】:

我正在处理连接到 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 = 到该代码的 10% 条来创建 100% xp 条值:

$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代码吗?
  • 我建议另一种方法:不要保存进度,而是保存 XP 和当前级别。查询当前经验值和等级后,根据等级计算经验值和进度。
  • @mrksr 为什么保存进度也是个坏主意?目前我正在保存级别、xp 和 max xp。你介意展示你的想法以及为什么它更好吗?谢谢
  • 首先,让应用程序而不是数据库层进行计算是一种惯例。这应该用于保存和检索数据,这使您的应用程序更易于理解、调试等。如果你只是保存 xp 和当前等级,你不需要重置任何东西,只需添加更多 xp 和等级,这是微不足道的 sql。 ;-)

标签: javascript php html css sql


【解决方案1】:

你必须使用 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);
});

“更新”函数检查进度,并在需要时调用重置函数,该函数调用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多