Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更改类名不通过所有if和elseif语句_Javascript_Css_Class_Getelementbyid_Classname - Fatal编程技术网

Javascript 更改类名不通过所有if和elseif语句

Javascript 更改类名不通过所有if和elseif语句,javascript,css,class,getelementbyid,classname,Javascript,Css,Class,Getelementbyid,Classname,对换班有意见。如果我将像素硬编码到样式更改中,但希望使用类和CSS获得更干净的版本,我可以让它工作。目标是由于宽度百分比的值,使像素更改大小越来越大。这部分工作正常,但麻烦的部分是更改类以更改条的颜色。由于某些原因,它没有正确地通过if语句,只是保持绿色直到死亡(healthPercent为零或更少),当它达到零,然后变为红色。我不太明白为什么它通过了第一个if检查,而没有通过其余的检查。有没有办法解决这个问题 编辑:我正在做一个游戏。我只是想澄清一下 JAVASCRIPT displayLif

对换班有意见。如果我将像素硬编码到样式更改中,但希望使用类和CSS获得更干净的版本,我可以让它工作。目标是由于宽度百分比的值,使像素更改大小越来越大。这部分工作正常,但麻烦的部分是更改类以更改条的颜色。由于某些原因,它没有正确地通过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';
    }
}

您的代码片段似乎是根据您描述的内容工作的——假设您的HTML看起来像

var-pixelMod=2.3;
风险值百分比=10;
var lifeBar='player_lifeBar';
displayLifeBar=函数()
{
document.getElementById(lifeBar.style.width=healthPercent+'px';
var criticalife=25*pixelMod;
var lowLife=50*pixelMod;
var-hurtLife=75*pixelMod;

如果(你的问题我不清楚,特别是
一直保持绿色,直到死亡,当它达到零,然后变为红色
。为我工作。可能也想发布相关的HTML吗?谢谢运行代码,我一定是看错了区域。我会检查HTML的一面。很好的小测试代码,我在胡闹推送我想,只要看到这一点,我就可以更加简化代码的其余部分。
/* 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 */