gpt4 book ai didi

javascript - 如何在 javascript for 循环中为每个额外的 innerHTML 元素更改 css

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:09 25 4
gpt4 key购买 nike

<div id="test"></div>
<script type="text/javascript">

window.names=["heihachi", "forest law"];
window.values=[22, 31];
len=names.length
for (var i = 0; i < len; i++)
{
document.getElementById('test').innerHTML+= names[i];
//names[i].css=margin-left: values[i]px;//

}

</script>

这就是我想做的。除了第 10 行之外,for 循环完全按预期工作。我希望添加到该 innerHTML 的每个元素都移动不同的量。因此,heihachi 移动了 22 px,forest law 移动了 31 px,等等。对于添加的所有其他名称和值。我放在那里的是我的尝试(伪代码),但它不起作用。我怎样才能做到这一点?

最佳答案

我建议如下:

// declare variables in the local scope:
var names=["heihachi", "forest law"],
values=[22, 31],
// get a reference to the element outside of the loop (once, versus multiple times):
test = document.getElementById('test'),
// create an element in which to wrap the text:
span = document.createElement('span'),
// declare a variable which will become a reference to the node on which we're working:
_tmp;

// to move the element/words around we need to have 'position: relative':
span.style.position = 'relative';

// iterate over the names array:
for (var i = 0, len = names.length; i < len; i++)
{
// working on a clone of the 'span':
_tmp = span.cloneNode();
// appending a child textNode to that node:
_tmp.appendChild(document.createTextNode(names[i]));
// setting the left property of the Node's style object:
_tmp.style.left = values[i] + 'px';
// appending the node to the 'test' node:
test.appendChild(_tmp);
}

JS Fiddle demo .

然而,我更愿意在两个数组之间有一个明确的相关性,在这种情况下将数组转换为一个对象数组(每个对象都有一个名称 属性):

var namesAndPositions = [{
'name' : 'heihachi',
'value' : 22
},{
'name' : 'forest law',
'value' : 31
}],
test = document.getElementById('test'),
span = document.createElement('span'),
_tmp;

span.style.position = 'relative';

for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_tmp = span.cloneNode();
_tmp.appendChild(document.createTextNode(namesAndPositions[i].name));
_tmp.style.left = namesAndPositions[i].value + 'px';
test.appendChild(_tmp);
}

JS Fiddle demo .

如果目标是测量(每个元素左侧的 22px31px),那么您可以改用 display: inline-block 并设置 HTMLElement 节点的 marginLeft 属性:

// everything above this point in the code remains the same

span.style.display = 'inline-block';

for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_tmp = span.cloneNode();
_tmp.appendChild(document.createTextNode(namesAndPositions[i].name));
_tmp.style.marginLeft = namesAndPositions[i].value + 'px';
test.appendChild(_tmp);
}

JS Fiddle demo .

引用资料:

关于javascript - 如何在 javascript for 循环中为每个额外的 innerHTML 元素更改 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19613366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com