css - 伪元素过渡

标签 css 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> 

最佳答案

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

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

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

关于css - 伪元素过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812021/

相关文章:

javascript - 将类 ="transition"添加到网站上所有链接的脚本

html - 如何使用 FLEX 在 CSS 中包装 div

css - Codepen 上的奇怪错误消息

javascript - 禁用从 HTML 页面拖动图像

javascript - 使 UL 继承 Div 的最小高度/高度

css 过渡跳转到中心

python - 使用 Pytransitions 时没有关于触发器的建议

传单:两个 basemap 图层之间的混合

html - 模糊导航栏

javascript - 随着鼠标位置改变不透明度