【发布时间】:2019-01-18 15:40:12
【问题描述】:
在更改课程时遇到问题。如果我将像素硬编码到样式更改中,但想要使用类和 CSS 的更清晰的版本,我可以让它工作。目标是由于宽度的 healthPercent 值而使像素变化的大小越来越大。这部分有效,但麻烦的部分是更改类以更改条的颜色。出于某种原因,它没有正确地通过 if 语句,并且一直保持绿色直到死亡(对于 healthPercent 而言为零或更小),当它达到零然后变成红色时。我不太明白为什么它通过第一个 if 检查而不是其余的。有关如何解决此问题的任何想法?
编辑:我正在开发一款游戏。只是为了澄清。
JAVASCRIPT
displayLifeBar = function ()
{
pixelMod = 2.3; //added definition here but global on full code
healthPercent = 130; //added here for example but passed down
lifeBar = 'player_lifebar';
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
}
else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
}
else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
}
else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
}
else
{
document.getElementById(lifeBar).className = 'lifebar';
}
}
CSS
/* LIFEBAR COLORS STARTS */
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
/* LIFEBAR COLORS ENDS */
【问题讨论】:
-
你的问题我不清楚,特别是
just stays green until death, when it reaches zero and then turns red。 -
为我工作。可能也想发布相关的 HTML 吗?
标签: javascript css class getelementbyid classname