伪元素过渡

Pseudo elements transition

如果您将鼠标悬停在该元素上,过渡会起作用,但当您离开该元素时则不会。我该如何解决?

这是我的代码和我的 JSFiddle

.block{
    border: 2px solid grey;
    border-radius: 4px;
    height: 90px;
    margin: 0 auto;
    text-align: center;
    width: 110px;
    padding-top: 6px;
}

.fr:hover{
   -webkit-transition: all 0.4s ease 0s;
   -moz-transition: all 0.4s ease 0s;
   -ms-transition: all 0.4s ease 0s;
   -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
    position: relative; 
 border-top: 2px solid rgba(150, 200, 200, 1); 
 border-bottom: 2px solid rgba(0, 0, 0, 1);
} 

.fr:before, .fr:after {
   -webkit-transition: opacity 0.2s ease-in-out;
   -moz-transition: opacity 0.2s ease-in-out;
   -ms-transition: opacity 0.2s ease-in-out;
   -o-transition: opacity 0.2s ease-in-out;
    transition: opacity 0.2s ease-in-out;
    content: ""; 
    position: absolute; 
    background-image: linear-gradient(to bottom, rgba(150, 200, 200, 1) 0%, rgba(10, 20, 20, 1) 80%),    linear-gradient(to bottom, rgba(150, 200, 200, 1) 10%, rgba(10, 20, 20, 1) 100%);
    opacity: 0;
} 

.fr:hover:before, .fr:hover:after {
   -webkit-transition: opacity 0.2s ease-in-out;
   -moz-transition: opacity 0.2s ease-in-out;
   -ms-transition: opacity 0.2s ease-in-out;
   -o-transition: opacity 0.2s ease-in-out;
    transition: opacity 0.2s ease-in;  
    content: ""; 
    position: absolute; 
    background-image: linear-gradient(to bottom, rgba(155, 200, 200, 1) 0%, rgba(10, 20, 20, 1) 80%),    linear-gradient(to bottom, rgba(155, 200, 200, 1) 10%, rgba(10, 20, 20, 1) 100%);
    top: 0px; bottom: 0px; width: 2px; 
    opacity: 1;
} 

.fr:before { left: -2px; } 
.fr:after { right: -2px; }
<div class="block fr"></div> 

尝试在悬停之前在元素上放置过渡,以便它过渡回其原始状态。

.fr{
    -webkit-transition: all 0.4s ease 0s;
    -moz-transition: all 0.4s ease 0s;
    -ms-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

这里需要做很多事情。首先,您需要始终将过渡应用于 .block .fr 元素(因此它适用于鼠标移入和鼠标移出)。现在您仅在 :hover 状态期间应用转换:

.block {
    /* Add `transition: all 0.4s ease 0s;` */
    /* Add `position: relative;` */
}

.fr:hover {
    /* Remove `position: relative;` */
    /* Remove `transition: all 0.4s ease 0s;` */
}

这允许过度效果淡入和淡出。伪元素仍然存在一个问题 - 它们会进入和退出状态,而不是过渡。这是由于定位属性(topbottom 等)在 :hover 状态下存在,但在 static 状态下不存在:

.fr:before, .fr:after {
    /* Add `top: 0px; bottom: 0px; width: 2px;` */
} 

.fr:hover:before, .fr:hover:after {
    /* Remove `transition: opacity 0.2s ease-in;` */
    /* Redundant: `content: "";` */
    /* Redundant: `position: absolute;` */
    /* Redundant: `background-image: ...; */
    /* Remove `top: 0px; bottom: 0px; width: 2px;` */
}

当一切都说完了,这里是(大致)你剩下的:https://jsfiddle.net/vn5hdn45/3/