【问题标题】:Why does div.width not work when using clearInterval?为什么使用 clearInterval 时 div.width 不起作用?
【发布时间】: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


【解决方案1】:

您可以尝试将con.width 替换为con.offsetWidth

例如https://codepen.io/julien180/pen/JjJvqEd?editors=1111

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2021-07-27
    • 2013-01-17
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多