0

我正在编写一个 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%。

这意味着当数字 50 通过传入时,$_GET它将计算出 50% 的中间柱,不包括 5% 的第一个柱,这是错误的,它应该考虑前 5%,然后计算出 50%像素宽度?

如何更改百分比背后的数学以修复两个中间条,以便在应用 50% 时两个中间条的像素相等?

4

3 回答 3

1

根本没有充分的理由使用像素。将你的 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%;
}

或者first,如果你不想last被带离 100%:

<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;
}
于 2013-01-09T18:46:41.860 回答
0

您应该将宽度转换为整数,因为它也可以是浮点数,您可以通过简单地从总宽度中减去第一个条的宽度来计算第二个条的宽度。

// 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;
于 2013-01-09T18:41:37.947 回答
-1

您应该将 $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;
}
于 2013-01-09T18:35:48.257 回答