【问题标题】:Dynamically changing the style of an element in a loop在循环中动态改变元素的样式
【发布时间】:2025-12-09 01:25:01
【问题描述】:

我试图让我的 3 个元素 marginLeft 彼此不同,之后的每个元素都比前一个元素大 300px。显然,将它作为字符串的 'px' 是障碍,但我不知道如何克服它。

function render() {
  var gElOptions = document.querySelector('.options');

  for (var i = 0; i < 3; i++) {
    var elOptionBtn = document.createElement('button');

    gElOptions.appendChild(elOptionBtn);
    elOptionBtn.setAttribute('class', `option-${i}`);
    var elOption = document.querySelector(`.option-${i}`);
    elOption.style.marginLeft = 1000 + 'px';
    // The problematic line:
    if (elOption.style.marginLeft === 1000 + 'px') elOption.style.marginLeft -= 300 + 'px';
  }
}
<body onload="render()">
  <div class="options">

  </div>
</body>

【问题讨论】:

  • 这应该由 css 完成。 nth-of-type 或 child 然后设置边距。如果您使用一些预处理器(sass,less),那么您可以循环执行。
  • 嗨@Robert,我很难让它工作。我确实尝试在 css 中设置 marginLeft,但我仍然面临动态更改其他 2 个按钮的问题。我该怎么做?

标签: javascript styles margin


【解决方案1】:

function render() {
    var gElOptions = document.querySelector('.options');

    for (var i = 0; i < 3; i++) {
        var elOptionBtn = document.createElement('button');
        elOptionBtn.innerHTML = i
        gElOptions.appendChild(elOptionBtn);
        elOptionBtn.setAttribute('class', `option-${i}`);
        //var elOption = document.querySelector(`.option-${i}`);
        elOptionBtn.style.marginLeft = i*300 + 'px';
        // The problematic line:
        //if (elOption.style.marginLeft === 1000 + 'px') elOption.style.marginLeft -=  300 + 'px';
    }
}

render()
&lt;div class="options"&gt;&lt;/div&gt;

【讨论】:

  • 嗨艾伦,虽然它最终将按钮设置在相同的位置(谢谢你),但它不允许我将它们调整到我想要在页面上的正确位置(试图CSS 上的 marginLeft/Right 它们都弄乱了代码的结果,突然它们不再以相等的距离彼此相邻对齐,而是一个不均匀地在另一个上方。
  • 你的意思是当你在*窗口中运行代码的时候?
  • 运行上述代码时点击Full page查看最终结果。
  • 我的意思是我的项目。关键是在 gElOptions 的元素中拥有按钮(包含按钮的 div)。当我运行代码时 - 虽然它最终使用 marginLeft 将它们设置为彼此相等的距离,但我无法将它们保持在 gElOptions 的视觉图像的边界内,并且 2 个按钮逃脱了边界。
【解决方案2】:

Js 仅用于动态添加按钮。 (右箭头,左箭头)。

每个按钮的边距在 css 中设置。

const container = document.querySelector('div');

const addButton = () => {
  const button = document.createElement('button');
  button.textContent = "test"
  container.appendChild(button);
}

const delButton = () => {
 container.lastChild?.remove()
}

window.addEventListener("keydown", ({key}) => {
  switch(key){
    case "ArrowLeft": {
      delButton();
      break;
    }
    case "ArrowRight": {
       addButton();
    }
  }
  
})
button{
  margin-left: 5px;
}
button:nth-child(1){
  margin-left: 10px;
}
button:nth-child(2){
  margin-left: 20px;
}
button:nth-child(3){
  margin-left: 30px;
}
button:nth-child(4){
  margin-left: 40px;
}
button:nth-child(5){
  margin-left: 50px;
}
button:nth-child(6){
  margin-left: 50px;
}
&lt;div&gt;

【讨论】: