[英]Moving Element from top to bottom with setInterval
我想從上到下移動一個元素,使用setInterval
每 10 毫秒向其頂部添加 1px
這是我的代碼:
var cir1 = document.getElementsByClassName('cir1'); function moveCir(elem) { var elemTop = elem.style.top + 'px'; elem.style.top = elemTop; elem.style.top = elemTop + 1 + 'px' ; setInterval(function () { moveCir(elem) },10) }
.cir1 { height: 100px; width: 100px; margin: 30px 100px; border: 1px solid #AC0D67; border-radius: 100%; display: inline-block; }
<button onclick="moveCir(cir1)" id="start">Start</button> <div class="cir1"></div>
但我不知道為什么它不起作用
我想你想要這個:
function moveCir(elem) { var elemTop = elem.getBoundingClientRect().top; if (elemTop < 200) { elem.style.top = elemTop + 1 + 'px'; setTimeout(function() { moveCir(elem) }, 100) } }
#cir1 { height: 100px; width: 100px; margin: 30px 100px; border: 1px solid #AC0D67; border-radius: 100%; display: inline-block; position: absolute; }
<button onclick="moveCir(cir1)" id="start">Start</button> <div id="cir1"></div>
但是,我必須警告您:
這是一個壞主意 :
onclick="moveCir(cir1)"
更好的解決方案在這里:
var moveCir = function f(elem) { var elemTop = elem.getBoundingClientRect().top; if (elemTop < 200) { cir1.style.top = elemTop + 1 + 'px'; setTimeout(f, 100, elem); } }; var cir1 = document.getElementById('cir1'); document.getElementById('start').addEventListener('click', function() { moveCir(cir1) }, false);
#cir1 { height: 100px; width: 100px; margin: 30px 100px; border: 1px solid #AC0D67; border-radius: 100%; display: inline-block; position: absolute; }
<button id="start">Start</button> <div id="cir1"></div>
var cir = document.getElementsByClassName('cir1')[0];
var cirTop = cir.style.top;
function moveCir() {
cirTop++;
cir.style.top = cirTop + 'px';
}
setInterval(moveCir, 10);
類名被視為一個數組。 您尚未在document.getElementsByClassName('cir1')
包含 [0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.