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

在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
    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;
    ?>
    
    点赞 评论
  • duangan4070
    duangan4070 2016-09-15 23:00

    Set $top as:

     $top = floor (($i -1) / 2) * 342;
    
    点赞 评论

相关推荐