Tim*_*Tim 5 html css css-transitions css-animations
我正在寻找一种使CSS悬停过渡动画的方法。而且我希望保持纯CSS。如果没有,我将使用jquery作为备份。
这将是我的目标:
具有内容div的容器。当悬停时,它会动画/向上滑动。如图所示:

我已经尝试过类似下面的代码。问题是过渡不使auto零件动画。内容的高度可变。因此,每次都不同。(每个网格项目)
.my_container{
position: relative;
width: 100%;
padding-top: 160%;
overflow: hidden;
}
.my_container > .my_content{
position: absolute;
top: 0;
bottom: auto;
left: 0;
right: 0;
}
.my_container > my_content:hover{
top: auto;
bottom: 0;
}
.my_container * {
-webkit-transition: all .6s ease-in-out;
-moz-transition: all .6s ease-in-out;
-o-transition: all .6s ease-in-out;
transition: all .6s ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)
我考虑过,transform: translateY();但据我所知,这仅适用于百分比和px。
目标是在悬停时从上到下对齐动画。
(打上这个让我想到了另一件事。这在移动设备上是没用的,对吗?:))
如果子元素和父元素之间存在已知关系,则可以轻松地应用翻译。
这是一个基本的例子
.box {
height:100px;
width:50px;
margin:50px;
border:3px solid;
position:relative;
}
.box:before {
content:"";
position:absolute;
top:0;
width:100%;
height:143%;
background:red;
transition:1s all;
}
.box:hover::before {
transform:translateY(-30%)
/* 143% is 100%
100% is X% ---> X = 70% so we move by (100% - 70%)
*/
}Run Code Online (Sandbox Code Playgroud)
<div class="box">
</div>Run Code Online (Sandbox Code Playgroud)
您可以使用CSS变量表示:
.box {
height:100px;
width:50px;
margin:50px;
display:inline-block;
border:3px solid;
position:relative;
}
.box:before {
content:"";
position:absolute;
top:0;
width:100%;
height:calc(var(--p)*1%);
background:red;
transition:1s all;
}
.box:hover::before {
transform:translateY(calc((10000/var(--p))*1% - 100%))
}Run Code Online (Sandbox Code Playgroud)
<div class="box" style="--p:143;">
</div>
<div class="box" style="--p:170;">
</div>
<div class="box" style="--p:120;">
</div>Run Code Online (Sandbox Code Playgroud)
更新
如果是动态内容,则可以添加如下所示的小型JS代码:
$('.box').each(function() {
var h0 = $(this).height();
var h1 = $(this).find('span').height();
$(this).css('--t',(h0-h1));
})Run Code Online (Sandbox Code Playgroud)
.box {
height: 100px;
width: 50px;
margin: 50px;
display: inline-block;
border: 3px solid;
position: relative;
}
.box span {
position: absolute;
top: 0;
width: 100%;
background: red;
transition: 1s all;
}
.box:hover span{
transform: translateY(var(--t));
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed est ex, pretium tempus turpis vitae, </span>
</div>
<div class="box">
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div class="box">
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed est ex, pretium </span>
</div>Run Code Online (Sandbox Code Playgroud)