这是代码 我没有得到offsetTop的区别..我在哪里做错了? 但如果我把个别的i和n值,输出来......
<html>
<body>
<div class="names" style="position: absolute; left: 13px; top: 53px;">
<span id="f12" style="font-size: 12px; vertical-align: baseline; color: red;">Joe</span>
</div>
<div class="names" style="position: absolute; left: 13px; top: 64px;">
<span id="f12" style="font-size: 12px; vertical- align: baseline; color: blue;">John</span>
</div>
<div class="names" style="position: absolute; left: 13px; top: 76px;">
<span id="f12" style="font-size: 12px; vertical-align: baseline; color: red;">Jony</span>
</div>
<div class="names" style="position: absolute; left: 13px; top: 89px;">
<span id="f12" style="font-size: 12px; vertical-align: baseline; color: blue;">Jonson</span>
</div>
<div class="names" style="position: absolute; left: 13px; top: 100px;">
<span id="f12" style="font-size: 12px; vertical-align: baseline; color: red;">Juni</span>
</div>
<div class="names" style="position: absolute; left: 13px; top: 113px;">
<span id="f12" style="font-size: 12px; vertical-align: baseline; color: blue;">Juno</span>
</div>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("div");
var i = 0;
var n;
var gap = "";
do {
n = i + 1;
gap += x[n].offsetTop - x[i].offsetTop + " ";
i++;
}
while (i < x.length);
document.getElementById("demo").innerHTML = gap;
}
</script>
</body>
</html>
我没有得到offsetTop的区别..我在哪里做错了? 但如果我把个别的i和n值,输出来......
由于
答案 0 :(得分:1)
你能试试吗,https://jsfiddle.net/7yhp7a8g/稍微改变了代码
function myFunction() {
var x = document.getElementsByTagName("div");
var i=0;
var n = i;
var gap = " ";
do{
i++;
gap += x[i].offsetTop - x[n].offsetTop + " ";
n=i;
}
while (i < x.length - 1);
document.getElementById("demo").innerHTML = gap;
}
答案 1 :(得分:0)
如果设置n = i + 1
,最终会得到一个大于收藏集长度的索引。删除该语句,它将起作用:
do{
n = i;
gap += x[n].offsetTop-x[i].offsetTop + " ";
i++;
}