【问题标题】:calculate div width in percentage from time duration根据持续时间以百分比计算 div 宽度
【发布时间】:2018-10-21 10:28:14
【问题描述】:

我正在尝试根据持续时间百分比计算 div 宽度

我有三个 div 根据两个日期之间的持续时间给它们宽度和填充背景颜色

lengthdiv1=2018-4-01 22:31:59 - 2018-01-01 00:00:00
lengthdiv2=2018-10-10 22:31:59 - 2018-4-01 22:31:59
lengthdiv3=2018-12-31 23:59:59 - 2018-10-10 22:31:59

 $maxWidth = 100; // total percentage 
$eventStart = strtotime('2018-01-01 00:00:00');
$eventEnd   = strtotime('2018-4-01 22:31:59');
$eventLength = $eventEnd - $eventStart;
$maxLength = 86400;
$ratio = $eventLength / $maxLength; 
$width = round($ratio * $maxWidth);

我尝试以百分比应用 div 宽度的 HTML 代码

 <div class="daylight">
    <div class="daytime standard" style="width: 20%; background: #D1F1AD;border-left: none;">3m 23d h4</div>
    <div class="daytime summer" style="width: 60%; background: #FDE492; text-align: center">3m 23d h4</div>
    <div class="daytime standard1" style=" background: #D1F1AD;width: 20%; ">3m 23d h4</div>
  </div>

【问题讨论】:

    标签: php html math calculator


    【解决方案1】:

    这应该是必要的。

    <?php
        $dur1 = (strtotime("2018-04-01 22:31:59")) - (strtotime("2018-01-01 00:00:00"));
        $dur2 = (strtotime("2018-10-10 22:31:59")) - (strtotime("2018-4-01 22:31:59"));
        $dur3 = (strtotime("2018-12-31 23:59:59")) - (strtotime("2018-10-10 22:31:59"));
    
        $totDur = $dur1 + $dur2 + $dur3;
    
        $wid1 = round($dur1 * 100 / $totDur);
        $wid2 = round($dur2 * 100 / $totDur);
        $wid3 = round($dur3 * 100 / $totDur);
    
        echo $wid1, " ", $wid2, " ", $wid3;
    

    这里的策略是这样的

    1. 使用 php 的 int strtotime ( string $time [, int $now = time() ] ) 将给定的字符串转换为以秒为单位的时间戳(从 epoch timestamp 开始)。
    2. 以秒为单位获取差异。
    3. 找出总的差异。
    4. each difference / total difference 转换为百分比,将round 转换为最接近的整数。

    【讨论】:

    • 当我舍入宽度最接近的值时,有时宽度可能会从 100% 增加并且 div 布局被破坏
    • 当然,如果是这种情况,您可以将$wid3 = round($dur3 * 100 / $totDur); 替换为$wid3 = 100 - ($wid1 + $wid2);。它将始终确保宽度的总和不会超过 100。是的,存在精度问题,但由于这是出于查看目的,我认为不需要考虑这一点。
    猜你喜欢
    • 2016-01-23
    • 2014-05-05
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多