【问题标题】:How to move element from its position to a center如何将元素从其位置移动到中心
【发布时间】:2021-02-06 03:52:23
【问题描述】:
我有三个元素,单击其中一个元素后,我想将其移动到中心,但要从其位置移动,例如 1 秒。另外,我想在框从 150px 增加到 200px 的时间内增加淡入淡出的文本并显示另一个文本,但现在我只是不知道如何将它集中在点击上。我做到了,但它从右下角到中心,但我希望它离开它的位置。
另外,我尝试使用 $(this) 来获取某些 div,但它不起作用
$(document).ready(function(e) {
$('.second').click(e => {
$('.second').addClass('red')
})
});
.main {
display: flex;
gap: 15px;
height: 90vh;
justify-content: center;
align-items: center;
position: relative;
}
.block {
width: 150px;
height: 100px;
box-shadow: 0px 0px 3px #000;
}
.red {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 150px;
height: 150px;
transition: 1s ease;
color: red;
@keyframes rise;
@keyframes rise {
0% { width: 200px; height: 200px }
100% { width: 150px; height: 150px }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='main'>
<div class="first block">Hello</div>
<div class="second block">Hi</div>
<div class="third block">hello</div>
</div>
【问题讨论】:
标签:
html
jquery
css
animation
【解决方案2】:
这是因为一切都在转变,
在您的代码中居中 div 的顺序是这样的:
首先,它的位置变得绝对
然后它转到右下角,因为你有top 50%; left 50%;
然后因为transform: translate( -50%, -50%)又回到中心
您可以通过以下方式修复它:
- 将居中方法更改为边距
$(document).ready(function(e) {
$('.second').click(e => {
$('.second').addClass('red')
})
});
.main {
display: flex;
gap: 15px;
height: 90vh;
justify-content: center;
align-items: center;
position: relative;
}
.block {
width: 150px;
height: 100px;
box-shadow: 0px 0px 3px #000;
}
.red {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 150px;
height: 150px;
transition: 1s ease;
color: red;
@keyframes rise;
@keyframes rise {
0% { width: 200px; height: 200px }
100% { width: 150px; height: 150px }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='main'>
<div class="first block">Hello</div>
<div class="second block">Hi</div>
<div class="third block">hello</div>
</div>
这样,div 无处可去,只到中心。
- 第二种方法是不转换
position和transform
$(document).ready(function(e) {
$('.second').click(e => {
$('.second').addClass('red')
})
});
.main {
display: flex;
gap: 15px;
height: 90vh;
justify-content: center;
align-items: center;
position: relative;
}
.block {
width: 150px;
height: 100px;
box-shadow: 0px 0px 3px #000;
}
.red {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 150px;
height: 150px;
transition: 1s ease;
transition-property: width, height, color;
color: red;
@keyframes rise;
@keyframes rise {
0% { width: 200px; height: 200px }
100% { width: 150px; height: 150px }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='main'>
<div class="first block">Hello</div>
<div class="second block">Hi</div>
<div class="third block">hello</div>
</div>
transition-property 属性定义了要转换的属性,所以我输入了:width、height 和 color。您可以更改要转换的内容