Tom*_*myF 5 css css-transitions css-animations
我position: fixed;在页面的右上角有一个元素。
我希望它在单击时“增长并移动”到屏幕的中心。
我知道的最好的解决方案是将某些内容放置在页面的中心位置
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Run Code Online (Sandbox Code Playgroud)
如果我最初使用top和left属性放置元素,那么一切都会很好,但是如果最初使用right而不是元素放置动画,则动画中会出现令人讨厌的跳跃left。
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Run Code Online (Sandbox Code Playgroud)
const myFunc = function() {
let f = document.getElementById('element')
if (f.className.includes('bar')) {
f.className = 'foo'
} else {
f.className = 'foo bar'
}
}Run Code Online (Sandbox Code Playgroud)
.wrapper {
position: relative;
width: 100%;
height: 100%;
}
.foo {
position: fixed;
top: 20px;
right: 20px;
width: 200px;
height: 50px;
background-color: blue;
transition: 0.5s all;
}
.bar {
position: fixed;
top: 50%;
left: 50%;
width: 500px;
height: 500px;
background-color: red;
transform: translate(-50%, -50%);
transition: 0.5s all;
}Run Code Online (Sandbox Code Playgroud)
如何摆脱动画中向水平中心的初始跳跃?(即我想要“缩小到右上角”的反义词,这里一切正常。)
您只需将状态从右更改为左即可foo。
这也意味着您将 translate 属性更改为 :translate(50%,-50%);因为 tanslateX 值应该从左到右以使元素居中:
const myFunc = function () {
let f = document.getElementById('element')
if(f.className.includes('bar')) {
f.className = 'foo'
}
else {
f.className = 'foo bar'
}
}Run Code Online (Sandbox Code Playgroud)
.wrapper {
position: relative;
width: 100%;
height: 100%;
}
.foo {
position: fixed;
top: 20px;
right: 20px;
width: 200px;
height: 50px;
background-color: blue;
transition: 0.5s all;
}
.bar {
position: fixed;
top: 50%;
right: 50%;
width: 500px;
height: 500px;
background-color: red;
transform: translate(50%, -50%);
transition: 0.5s all;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="foo" id="element" onclick="myFunc()">
</div>
</div>Run Code Online (Sandbox Code Playgroud)
附带说明一下,如果您知道元素在两种状态下的大小,则可以仅在顶部和右侧属性上进行转换,calc()如下所示:
const myFunc = function() {
let f = document.getElementById('element')
if (f.className.includes('bar')) {
f.className = 'foo'
} else {
f.className = 'foo bar'
}
}Run Code Online (Sandbox Code Playgroud)
.wrapper {
position: relative;
width: 100%;
height: 100%;
}
.foo {
position: fixed;
top: 20px;
right: 20px;
width: 200px;
height: 50px;
background-color: blue;
transition: 0.5s all;
}
.bar {
position: fixed;
top: calc(50% - 250px);
right: calc(50% - 250px);
width: 500px;
height: 500px;
background-color: red;
transition: 0.5s all;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="foo" id="element" onclick="myFunc()">
</div>
</div>Run Code Online (Sandbox Code Playgroud)
这会更改动画轨迹,并防止该元素同时通过该transform属性在一个方向(上/右)和其他方向上进行动画处理。