我从数组中获取两个值:
$target = $data->data[2][32][3];
在本例中$target = 9.83%
。
$clicks = $data->data[1][32][3];
在本例中$clicks = 7.15%
。
我有一个由 .outer div
(代表背景 div,包含所有其他 div 的 div)和 .inner div
(填充外部...您可以将其想象为一个显示完成百分比的条形图)和一个 .target div
(表示虚线/.inner div 必须达到的目标..在某些情况下像这个一样,它超出了目标:.inner > .target
)。
$target = 9.83%;
$bar_width = '200px';
$clicks = 7.15%;
$base = max($target, $clicks);
.outer,
.inner,
.target {
height: 14px;
margin-bottom: 5px;
}
.outer {
background-color: #cccccc;
width: 200px;
margin: 20px auto;
position: relative;
font-size: 10px;
line-height: 14px;
font-family: sans-serif;
}
.inner {
background-color: green;
position: absolute;
z-index: 1;
text-align: right;
width: calc(200 / 100 * <?php echo $base; ?>);
border-right: 2px solid black;
}
.inner:after {
content: ' 7.15%';
display: inline-block;
left: 10px;
position: relative;
height: 100%;
top: -14px;
margin-left: 17px;
}
.target {
background-color: transparent;
width: 19px;
position: absolute;
z-index: 2;
color: black;
text-align: right;
border-right: 2px dotted black;
}
.target:after {
content: 'Target: 9.83%';
display: inline-block;
left: 28px;
position: relative;
height: 100%;
top: 14px;
margin-left: -60px;
}
<div class="outer">
<div class="target" style="width: calc(<?php echo $bar_width; ?> / 100 * (<?php echo $target; ?> / <?php echo $base; ?> * 100))">
</div>
<div class="inner" style=" width: calc(<?php echo $bar_width; ?> / 100 * (<?php echo $clicks; ?> / <?php echo $base; ?> * 100))">
</div>
</div>
所以我的问题是,超出目标后,内部 div 应该完全填充外部 div。
最佳答案
好吧,首先让我们弄清楚如何计算宽度:
$bar_width = '200px';
$target = 9.83 / 100;
$clicks = 7.15 / 100;
将百分比值除以 100,得到一个可以乘以条形总宽度的值。您也不需要正在进行的“基本”计算。
<div class="outer">
<div class="target" style="width: calc(<?php echo $bar_width; ?> * <?php echo $target; ?>)">
</div>
<div class="inner" style=" width: calc(<?php echo $bar_width; ?> * <?php echo $clicks; ?>)">
</div>
</div>
然后更新宽度计算以计算条的百分比,即宽度 (200) 乘以百分比值。
需要注意的几件事:如果您无论如何都使用 PHP,则无需使用 CSS 计算操作(这样可以减轻客户端渲染的压力),并且如果您启用了速记 PHP你不需要继续写<?php echo foo ?>
:
<div class="target" style="width: <?= $bar_width * $target ?>">
-
<?= ?>
是一个简写的 PHP echo 语句
最后回答你的问题,你只需要在检索值后比较两个值,看看是否超出目标,如果超出,则将内部栏设置为占据整个栏:
$clicks = $clicks > $target ? 1 : $clicks;
这是一个工作文件:https://www.dropbox.com/s/33t0bmmik7y49i1/index.php?dl=0
关于javascript - 由两个 div 制成的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38053984/