Javascript 过渡不';我第一次不工作

Javascript 过渡不';我第一次不工作,javascript,css,css-transitions,Javascript,Css,Css Transitions,我对转换属性有问题。也就是说,它只在第一次之后工作。第一次没有过渡效应 JS代码: document.addEventListener("DOMContentLoaded", function() { var second = document.querySelector('.square'); if(second) { second.addEventListener("mouseenter", function() { var maxX = Math

我对转换属性有问题。也就是说,它只在第一次之后工作。第一次没有过渡效应

JS代码:

document.addEventListener("DOMContentLoaded", function() {

  var second = document.querySelector('.square');

  if(second) {
      second.addEventListener("mouseenter", function() {
          var maxX = Math.floor(Math.random() * (window.innerWidth - 200));
          var maxY = Math.floor(Math.random() * (window.innerHeight - 200));
          this.style.left = maxX + 'px';
          this.style.top = maxY + 'px';
          this.style.transition = 'left 2s, top 2s';
      });
  }

 });
CSS代码:

* {
margin: 0;
padding: 0;
}

main {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}

.second {
height: 200px;
width: 200px;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
}
编辑:

更新:


将转换移动到CSS不会改变任何东西。正方形必须居中,不能离开窗口。

移动
转换
顶部
左侧
到css-在设置新的X和Y之前,浏览器应该知道从和如何转换到css的内容

document.addEventListener(“DOMContentLoaded”,function()){
var second=document.querySelector('.square');
如果(秒){
addEventListener(“mouseenter”,function()){
var maxX=Math.floor(Math.random()*(window.innerWidth-200));
var maxY=Math.floor(Math.random()*(window.innerHeight-200));
this.style.left=maxX+'px';
this.style.top=maxY+'px';
});
}
});
.square{
背景:红色;
高度:200px;
宽度:200px;
位置:绝对位置;
显示器:flex;
证明内容:中心;
对齐项目:居中;
过渡:左2s,上2s;
排名:0;
左:0;
}


您能提供一个JSFIDLE吗?因此,很容易理解我的猜测是因为您正在使用JS添加转换,将其移动到CSSI添加的JSFIDLE。我把它移到CSS上,效果是一样的。这没关系,但当顶部为0,左侧为0时,正方形不居中。“我需要让这个正方形居中。@本,你可以在我编辑的答案中看到最初如何将你的正方形居中。是的,我现在很清楚,但这样一来,正方形就跑出了窗口。@本编辑的答案。”