[英]How to change css for each additional innerHTML element in a javascript for loop
<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>
這就是我想做的。 for循環除第10行外完全按預期工作。 我希望添加到該innerHTML中的每個元素的移動量都不同。 因此,heihachi移至22 px以上,森林法移至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小提琴演示 。
但是,我希望在兩個數組之間具有顯式關聯,在這種情況下,將數組轉換為對象數組(每個對象都具有name
和value
屬性):
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小提琴演示 。
如果目標是進行該測量(每個元素的左側分別為22px
和31px
),則可以改用display: inline-block
並設置HTMLElement-node的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小提琴演示 。
參考文獻:
這是一個更簡單的示例:
window.names=["heihachi", "forest law"];
window.values=[22, 31];
var len=names.length;
var test = document.getElementById('test');
for (var i = 0; i < len; i++)
{
var elm = document.createElement("span")
elm.innerHTML = names[i];
elm.style.marginLeft = values[i] + 'px';
test.appendChild(elm);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.