只更改alpha未知颜色

时间:2014-08-10 08:51:14

标签: css css3

我的课程很少:

.overlay-blue {background-color: rgba(0,123,238,0.9);}
.overlay-orange { background-color:rgba(240,116,7,0.9); }
.overlay-purple { background-color:rgba(126,64,228,0.9); }
.overlay-green { background-color:rgba(57,151,95,0.9) }
.overlay-pink { background-color:rgba(173,33,106,0.9); }
.overlay-light-blue {background-color:rgba(0,183,168,0.9) }
.overlay-red {background-color:rgba(235,50,89,0.9); }


.overlay:hover
{
    -webkit-animation-duration: 0.5s;
    -webkit-animation-name: fadeInFromNone;
    background-color: rgba(0,0,0,0.3);
}

@-webkit-keyframes fadeInFromNone {
    0% {display:block; background-color: rgba(0,0,0,0.9);}
    1% {display: block ; background-color: rgba(0,0,0,0.89);}
    100% {display: none ; background-color: rgba(0,0,0,0.3);}
}

`

这种悬停功能运行良好,但是由于线条的原因,它会在动画处理时将叠加层变为黑色

0% {display:block; background-color: rgba(0,0,0,0.9);}

这是有道理的。

有没有办法调暗alpha通道而不重复每种颜色的代码?

1 个答案:

答案 0 :(得分:3)

目前的方法没有简单的方法,因为不可能单独定位rgba()属性中的alpha通道并进行更改。但是,您可以执行的操作不是在元素上设置背景颜色,而是将伪元素的背景颜色设置为其父元素的完整维度,并仅声明rgb()值。可以将alpha通道更改委派给opacity属性。我称之为伪元素方法:

伪元素方法

/* Define BG colours of pseudo element instead */
.overlay-blue::before { background-color: rgb(0,123,238);}
.overlay-orange::before { background-color:rgb(240,116,7); }
/* and more... */

/* Set relative positioning of parent element */
.overlay {
    position: relative;
}

/* Stretch pseudo element, declare empty content so it will show */
.overlay::before {
    content: '';
    opacity: .9;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    transition: all .5s ease-in-out;
    z-index: -1;
}

/* Change opacity when parent element is hovered upon */
.overlay:hover::before {
    opacity: 0.3;
}

当然,这是您的问题(see demo fiddle here)的一个相当基本的实现,因为我不知道您想要使用动画关键帧实现的确切细节。好消息是伪元素也可以动画:)

SASS方法

更好:或者,您可能需要考虑使用CSS预处理器(SCSS,LESS),以便您可以使用变量,而不必重复重新声明背景颜色。 See the demo here

您可以使用以下mixin:

/* Declare mixin */
@mixin overlayColor($color) {
    background-color: rgba($color, 0.9);
    &:hover { background-color: rgba($color, 0.3); }
}

/* Use @include for each colour class, you only have to declare the rgb(a) values */
.overlay {
    margin-bottom: 10px;
    padding: 20px;
    position: relative;
    transition: all .5s ease-in-out;

    &.overlay-blue {
        @include overlayColor(rgb(0,123,238));
    }
    &.overlay-orange {
        @include overlayColor(rgb(240,116,7));
    }
    /* and more... */
}
相关问题