在for循环中动态增加css元素的宽度


Dynamically increment width of css element in a for loop

编辑:我发现了,它在我下面的另一个答案中。

我想在php中呈现一个图形,可以创建列,但是当我尝试增加百分比以对应于.inner类的css宽度时,它不会为数组中的每个元素增加。如何增加数组中每个元素的宽度?

$percentage = array(0.2,0.4,0.5,0.6,0.7,0.8);
for($i=0;$i<6;$i++){
echo "<div class='outter'>
<div class='inner'>"; echo $percentage[$i]; echo "
</div>
</div>";
echo "<style type='text/css'>";
echo ".outter{height:25px;width:500%;border-right:solid 1px #000;}";
echo ".inner{height:25px;width:";echo $percentage[i]; echo "%;border-right:solid 1px #000;background-color:#02abff;}";
echo "</style>";
}

我可以在HTML和CSS中做,但我想做php。谢谢。

不确定您是否已经注意到,但您在那里的实际值是0.X%,这不是一个有效的宽度。您可能需要将该值乘以10(或100)以得到2%(或20%)。

$percentage = array(0.2,0.4,0.5,0.6,0.7,0.8);
foreach ($percentage as $key => $val) {
    echo "<div class='outter'>
        <div class='inner'>";
    echo $val;
    echo "</div>
        </div>";
    echo "<style type='text/css'>";
    echo ".outter{height:25px;width:500%;border-right:solid 1px #000;}";
    echo ".inner{height:25px;width:";
    echo $val * 10;
    echo "%;border-right:solid 1px #000;background-color:#02abff;}";
    echo "</style>";
}

我还改变了for循环,你有那里的foreach循环,这在处理数组时更有意义。

我发现了。我必须把样式放在html标签中:

foreach($percentage as $percent){
echo "<div class='outter' style='height:25px;width:500%;border-right:solid 1px #000;'>
<div class='inner' style='height:25px;width:"; echo $percent; echo "%;border-right:solid 1px #000;background-color:#02abff;'>"; echo $percent; echo "
</div>
</div>";
}