Переместите transition
, top
и left
в css - браузер должен знать, что переходить из и , как перейти, прежде чем устанавливать новые X и Y.
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';
});
}
});
.square {
background:red;
height: 200px;
width: 200px;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: left 2s, top 2s;
top: 0;
left: 0;
}
<div class="square">
</div>
РЕДАКТИРОВАТЬ 1
Если вы хотите изначально центрировать свой квадрат - добавьте это
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
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';
});
}
});
.square {
background:red;
height: 200px;
width: 200px;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: left 2s, top 2s;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="square">
</div>
РЕДАКТИРОВАТЬ 2
Принимая во внимание вашу скрипку - вы должны изменить свой maxX
и maxY
расчеты, потому что свойство transform
переместило центр вашего квадрата из "верхнего левого угла" в "центр центра":
document.addEventListener("DOMContentLoaded", function() {
var second = document.querySelector('.square');
if(second) {
second.addEventListener("mouseenter", function() {
var maxX = 100 + Math.floor(Math.random() * (window.innerWidth - 200));
var maxY = 100 + Math.floor(Math.random() * (window.innerHeight - 200));
this.style.left = maxX + 'px';
this.style.top = maxY + 'px';
});
}
});
* {
margin: 0;
padding: 0;
}
main {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.square {
height: 200px;
width: 200px;
position: absolute;
-webkit-box-shadow: 0px 0px 70px 5px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 0px 70px 5px rgba(0,0,0,0.5);
box-shadow: 0px 0px 70px 5px rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
transition: left 0.8s, top 0.8s;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
<main>
<div class="square">
<p>catch me!</p>
</div>
</main>