dongxiezhi0590 2016-09-15 22:28
浏览 74
已采纳

在php for循环中操作样式

I am trying to add some styles to some divs in a php for loop. For each alternative iteration the position style is set either 'left: 0%' or 'left:53.8462%', which seems to be working. But I can't figure out how to set the top style. For each consecutive two iterations the value of the top style is increased by 342px while the initial value is set to 0px. In other words, for the first and second loop, top style value is 0px, but in the second and third iteration their values are incremented by 342px and so forth. The desired html output is shown below.

In the following code this part echo ($counter % 6 == 1 ? 'top: 0px;' : 'top: 342px;'); needs to changed.

<?php $counter = 1; ?>
<?php for ($i = 0; $i < 4; $i++): ?>
<div class="card" style="position: absolute; 
    <?php echo ($i%2 ? 'left: 53.8462%;' : 'left: 0%;'); echo ($counter % 6 == 1 ? 'top: 0px;' : 'top: 342px;');?>">

    // content //

    <?php $counter++; ?>
    <?php endfor;
?>

Here is the desired html output:

<div class="card" style="position: absolute; left: 0%; top: 0px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 0px;">

</div>

<div class="card" style="position: absolute; left: 0%; top: 342px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 342px;">

</div>

<div class="card" style="position: absolute; left: 0%; top: 684px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 684px;">

</div>
  • 写回答

2条回答 默认 最新

  • dreamy6301 2016-09-15 22:53
    关注

    It would be easier if you started $counter at 0. Then the top is just half of the counter multiplied by 384.

    And in this case, $counter is the same as $i, so there's no need for two variables.

    <?php for ($i = 0; $i < 4; $i++): ?>
    <div class="card" style="position: absolute; 
        <?php echo ($i%2 ? 'left: 53.8462%;' : 'left: 0%;'); echo 'top: ' . floor($i/2)*384 . 'px;';?>">
    
        // content //
    
        <?php endfor;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)