[英]Coding a dynamic PHP css based progress bar - maths percent issue
我正在编写一个PHP进度条,它将通过为其指定的百分比数字进行更新,但是在计算百分比时遇到了问题。
我的代码当前如下:
的PHP
$percent = $_GET['percent'];
if($percent < 5)
//low-image.jpg
elseif($percent > 95)
//high-image.jpg
else{
$lowpercent = 100 - $percent;
$highwidth = 270 / 100 * $percent;
$lowwidth = 270 / 100 * $lowpercent;
的HTML
<div class="first"></div>
<div class="mid-first" style="width:<?=$highwidth?>px;"></div>
<div class="mid-second" style="width:<?=$lowwidth?>px;"></div>
<div class="last"></div>
的CSS
.first. mid-first, .mid-second, .last{
display:block;
float:left;
height:62px;
}
.first{
background:url(low.png);
width:31px;
}
.mid-first{
background:url(mid-first.png) repeat-x;
}
.mid-second{
background:url(mid-second.png);
}
.last{
background:url(high.png);
width:32px;
}
问题
此刻百分比的计算有些不正确,今天我的数学大脑似乎放错了位置...
有4个div,第一个和最后一个div分别占5%,因此占10%,然后中间div等于其他90%。
这意味着当通过$_GET
传递图50时,它将计算出50%的中间柱,不包括5%的第一柱,这是错误的,它应该考虑前5%,然后计算出50%像素宽度?
如何更改百分比后面的数学值以固定两个中间条,以便当应用50%时,两个中间条的像素相等?
完全没有理由使用像素。 将div包裹在包含div的内部,并在CSS中使用百分比。
PHP:
$lowpercent = 100 - $percent;
HTML:
<div class="barwrapper">
<div class="first"></div>
<div class="mid-first" style="width:<?=($percent-5)?>px;"></div>
<div class="mid-second" style="width:<?=($lowpercent-5)?>px;"></div>
<div class="last"></div>
</div>
CSS:
.first{
background:url(low.png);
width:5%;
}
.last{
background:url(high.png);
width:5%;
}
或 ,如果您不希望从100%的first
和last
带走:
<div class="first"></div>
<div class="barwrapper">
<div class="mid-first" style="width:<?=($percent)?>px;"></div>
<div class="mid-second" style="width:<?=($lowpercent)?>px;"></div>
</div>
<div class="last"></div>
CSS:
.first{
background:url(low.png);
width:30px;
}
.last{
background:url(high.png);
width:30px;
}
您应该将宽度转换为整数,因为它也可以是浮点,并且可以通过简单地从总数中减去第一条宽度来计算第二条的宽度。
// We have already used 10 percents, so let's substract them
$percent = $percent - 10;
// We can't have negative percents, right?
if ($percent < 0) $percent = 0;
// Calculate 1st bar
$highwidth = (int) 270 / 100 * $percent;
// 100% - 1st bar = 2nd bar
$lowwidth = 270 - $highwidth;
您应先将$ highwidth和$ lowwidth转换为整数,然后再将它们写入CSS或HTML。 因为它们是浮点数。
我认为这可能有效:
$percent = $_GET['percent'];
if($percent < 5)
//low-image.jpg
elseif($percent > 95)
//high-image.jpg
else{
$highwidth = intval(270 / 90 * ($percent-5));
$lowwidth = 270 - $highwidth;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.