return鼠标不在上面时到初始位置

return to initial position when the mouse is no longer over it

当鼠标悬停在卡片上时,我有这种 3d 视差效果。但是我不知道如何在鼠标不在上面时return回到原来的位置。

let cardParallx = document.querySelector('.card-active');

cardParallx.addEventListener('mousemove',(e)=>{
    let x =(window.innerWidth/2 - e.pageX)/30;
    let y =(window.innerHeight/2 - e.pageY)/30;
    cardParallx.style.transform =`rotateX(${-y}deg) rotateY(${-x}deg)`;
});
<div class="card-active">
<img src="https://placekitten.com/200/300">
</div>

尝试将此添加到您的 CSS:

.card-active {
width: fit-content;
}

当用户鼠标未悬停并将图像旋转更改为默认值时,您的 JavaScript 会收到此消息:

cardParallx.addEventListener('mouseout', (e) => {
    let x =(window.innerWidth/2 - e.pageX)/30;
    let y =(window.innerHeight/2 - e.pageY)/30;
    cardParallx.style.transform =`rotateX(0) rotateY(0)`;
});

要获得类似的东西:

let cardParallx = document.querySelector('.card-active');

cardParallx.addEventListener('mousemove',(e)=>{
    let x =(window.innerWidth/2 - e.pageX)/30;
    let y =(window.innerHeight/2 - e.pageY)/30;
    cardParallx.style.transform =`rotateX(${-y}deg) rotateY(${-x}deg)`;
});

cardParallx.addEventListener('mouseout', (e) => {
    let x =(window.innerWidth/2 - e.pageX)/30;
    let y =(window.innerHeight/2 - e.pageY)/30;
    cardParallx.style.transform =`rotateX(0) rotateY(0)`;
});
.card-active {
width: fit-content
}
<div class="card-active">
<img src="https://placekitten.com/200/300">
</div>