You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript动态修改CSS样式 每遍历10个字典项增加padding值

实现方案

核心问题

你当前的逻辑已经正确维护了动态padding值,但最终写入DOM的<p>标签样式里固定写死了padding-bottom: 200px,没有引用你动态更新的padding变量,因此修改无法生效。
另外你当前通过Object.keys(MassAddressDict).indexOf(key)获取索引的写法性能较差,forEach方法本身支持直接获取当前遍历的索引值,无需额外计算。

修改后完整代码

var padding = 200
// 直接从forEach的第二个参数取索引,避免重复计算
Object.keys(MassAddressDict).forEach(function(key, index) {
    console.log(key + " " + MassAddressDict[key]);

    var recieverData = MassAddressDict[key]

    var senderInfo = combineSenderInfo();
    var receiverInfo = combineReceiverInfo(recieverData);
    
    // 如果你是要**每遍历完10个**再加padding,可以把判断条件改成 if(index > 0 && index % 10 === 0)
    // 原逻辑是第1个(索引0)就开始加,按需调整即可
    if (index % 10 === 0){
        padding = padding + 20
        console.log("Padding increased to ", padding)
    } 
    printWindow.document.write('<div style="display:flex;justify-content:space-between">');
    printWindow.document.write(senderInfo);
    printWindow.document.write('</div>');
    printWindow.document.write(receiverInfo);
    // 用模板字符串插入动态padding值
    printWindow.document.write(`<p style='padding-bottom: ${padding}px'></p>`)
});

补充说明

  • 如果不需要第1条数据就触发padding增加,只需要每满10条后再加,把判断条件调整为if(index > 0 && index % 10 === 0)即可
  • 如果运行环境不支持ES6模板字符串,也可以用字符串拼接实现:printWindow.document.write("<p style='padding-bottom: " + padding + "px'></p>")

内容的提问来源于stack exchange,提问作者e.iluf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:57:03