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条)

报告相同问题?