伪元素转换

时间:2015-11-19 18:47:33

标签: css css3 transition opacity pseudo-element

如果您悬停元素,则转换有效,但离开元素时则无效。我该如何解决?

这是我的代码和我的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> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

这里需要做很多事情。首先,您需要始终将转换应用于.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;` */
}

这允许过度效果淡入和淡出。伪元素仍然存在问题 - 它们会进入和退出状态,而不是转换。这是由于top状态中存在定位属性(bottom:hover等),而不是静态状态:

.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/

答案 1 :(得分:0)

尝试在悬停之前对元素进行转换,以便它转换回原始状态。

.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;
}