css 如何制作从屏幕中心到屏幕左上角的平滑动画?

yeotifhr  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(165)

我想制作一个图像动画,使其从屏幕中心平滑地移动到左上角
我尝试了过渡,但它没有按预期工作。

const acoustic = document.querySelector('.acoustic');
document.body.addEventListener('click', () => acoustic.classList.toggle('selected'));
.acoustic {
  background-color: blue;
  height: 100px;
  width: 90vw;
}

.acoustic .guitar{
    display: flex;
    position: relative;
    top: 50%;
    right: -50%;
    transform: translate(-50%, -50%);
    animation: fadeIn 0.5s ease-in-out 0.5s forwards;
    height: 10vw;
    width: 10vw;
    transition: all 0.3s ease;
    background-color: red;
}

.acoustic.selected .guitar {
    display: flex;
    position: relative;
    top: 0;
    left: 0;
    height: 5vw;
}
<p>Click anywhere</p>
<div class="acoustic"><div class="guitar"></div></div>
q35jwt9p

q35jwt9p1#

这个问题是因为你在第一个状态下指定right,然后在第二个状态下指定left,因为你没有改变相同的属性,所以你不会得到一个平滑的过渡。
right: -50%;更改为left: 50%

const acoustic = document.querySelector('.acoustic');
document.body.addEventListener('click', () => acoustic.classList.toggle('selected'));
.acoustic {
  background-color: blue;
  height: 100px;
  width: 90vw;
}

.acoustic .guitar{
    display: flex;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    animation: fadeIn 0.5s ease-in-out 0.5s forwards;
    height: 10vw;
    width: 10vw;
    transition: all 0.3s ease;
    background-color: red;
}

.acoustic.selected .guitar {
    display: flex;
    position: relative;
    top: 0;
    left: 0;
    height: 5vw;
}
<p>Click anywhere</p>
<div class="acoustic"><div class="guitar"></div></div>

相关问题