【发布时间】:2021-11-14 18:12:01
【问题描述】:
我使用 set 和 clearInterval 制作了一个移动到其容器宽度末端的正方形。
如果我将宽度添加为数字,它会停止,但是当我添加 container.width 时它不起作用:
var container = document.getElementById('container')
var square = document.getElementById('mySquare')
function theAll(sq,con){
var pos = 0;
var moving = setInterval(move,10)
function move(){
if(pos == con.width){
clearInterval(moving)}
else{
pos++
sq.style.left=pos + "px";}
}}
theAll(square,container)
#container{
font-size: 100%;
font-family: Comic Sans MS;
background-color: blanchedalmond;
border-radius: 5px;
padding: 0;
width: 100%;
height: 60%;
display: flex;
flex-direction: column;
}
#mySquare{
width: 5%;
height: 5%;
background-color: blueviolet;
position: relative;
}
【问题讨论】:
-
计算出的宽度不必是精确的整数。一个可能的解决方法是改用
pos >= con.width。
标签: javascript function if-statement setinterval clearinterval