我想从上到下移动一个元素,使用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>
&#13;
但我不知道为什么它不起作用
答案 0 :(得分:1)
我想你想要这个:
function moveCir(elem) {
var elemTop = elem.getBoundingClientRect().top;
if (elemTop < 200) {
elem.style.top = elemTop + 1 + 'px';
setTimeout(function() {
moveCir(elem)
}, 100)
}
}
&#13;
#cir1 {
height: 100px;
width: 100px;
margin: 30px 100px;
border: 1px solid #AC0D67;
border-radius: 100%;
display: inline-block;
position: absolute;
}
&#13;
<button onclick="moveCir(cir1)" id="start">Start</button>
<div id="cir1"></div>
&#13;
但是,我必须警告你:
这是个坏主意:
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);
&#13;
#cir1 {
height: 100px;
width: 100px;
margin: 30px 100px;
border: 1px solid #AC0D67;
border-radius: 100%;
display: inline-block;
position: absolute;
}
&#13;
<button id="start">Start</button>
<div id="cir1"></div>
&#13;
答案 1 :(得分:0)
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')