小编典典

具有自动高度的CSS3翻转卡

css

我正在使用一个教程使用CSS3和jQuery创建翻页卡效果,但在将高度调整为内容长度的同时仍然在中心水平位置翻转时遇到了问题。

码:

<div class="flip"> 
    <div class="card"> 
        <div class="face front"> 
            Front<br> Other text.<br> Other text.<br> Other text.<br> Other text.
        </div>

        <div class="face back"> 
            Back
        </div> 
    </div> 
</div>

body {
 background: #ccc;   
}
.flip {
  -webkit-perspective: 800;
   width: 400px;
   height: 200px;
    position: relative;
    margin: 50px auto;
}
.flip .card.flipped {
  -webkit-transform: rotatex(-180deg);
}
.flip .card {
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
  -webkit-transition: 0.5s;
}
.flip .card .face {
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-backface-visibility: hidden ;
  z-index: 2;
    font-family: Georgia;
    font-size: 3em;
    text-align: center;
}
.flip .card .front {
  position: absolute;
  z-index: 1;
    background: black;
    color: white;
    cursor: pointer;
}
.flip .card .back {
  -webkit-transform: rotatex(-180deg);
    background: blue;
    background: white;
    color: black;
    cursor: pointer;
}​

$('.flip').click(function(){
    $(this).find('.card').addClass('flipped').mouseleave(function(){
        $(this).removeClass('flipped');
    });
    return false;
});​


阅读 300

收藏
2020-05-16

共1个答案

小编典典

这是 jsFiddle 上的可行 解决方案。

JS:

$('.flip').click(function(){
    $(this).find('.card').addClass('flipped');
    return false;
}).mouseleave(function () {
    $('.flip > .card').removeClass('flipped');
});

var frontHeight = $('.front').outerHeight();
var backHeight = $('.back').outerHeight();

if (frontHeight > backHeight) {
    $('.flip, .back').height(frontHeight);
}
else if (frontHeight > backHeight) {
    $('.flip, .front').height(backHeight);
}
else {
    $('.flip').height(backHeight);
}

定义的高度不灵活,因此您看到的就是定义的高度。由于高度将不会保持恒定,因此前部或后部需要具有定义的高度,以匹配最高的元素。在示例中,.front较高,因此.back将其更新为相同的高度,从而使您能够在中心实现垂直翻转效果。

在您的示例中,mouseleave事件可以在动画期间的元素时触发。我以为您不希望这种情况发生,因此我更新了逻辑以.flipped在离开卡时删除它,该逻辑将在整个动画过程中保持其高度。我还清理了CSS,以减少冗余。希望这可以帮助!

2020-05-16