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

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧