悬停时从渐变背景切换到非渐变背景

3
我正在使用渐变来设置一个元素的背景颜色。问题是,我也有一个“hover”背景,但没有使用渐变。目前,当我悬停在一个具有类名“.tinted”的元素上时,它会闪烁,因为它首先显示没有背景,然后应用rgba(0,0,0,0.65)。是否有任何方法可以直接从背景:gradient(left, rgba(0,0,0,0.65), rgba(0,0,0,0.30))过渡到rgba(0,0,0,0.65)?
.tinted {
    transition: background-color 500ms linear;
    background: -webkit-linear-gradient(left, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background: -o-linear-gradient(right, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background: -moz-linear-gradient(right, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background: linear-gradient(to right, rgba(0,0,0,.65), rgba(0,0,0,.30));
}

.tinted:hover {
    background: rgba(0, 0, 0, 0.65);
}
3个回答

3

您需要使用 background-image 定义 gradients,并使用 background-color 定义 plain color

.tinted {
    transition: background-color 500ms linear;
    background-image: -webkit-linear-gradient(left, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background-image: -o-linear-gradient(right, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background-image: -moz-linear-gradient(right, rgba(0,0,0,.65), rgba(0,0,0,.30));
    background-image: linear-gradient(to right, rgba(0,0,0,.65), rgba(0,0,0,.30));
}

.tinted:hover {
    background-color: rgba(0, 0, 0, 0.65);
}

DEMO


它确实可以工作,但这样做会导致在悬停时仍然存在渐变。 - Scipion
你不能对 background-image 应用过渡效果,所以这是你能达到的最好效果。 - lmgonzalves

0

这是你可以在这个方法中使用的内容:

#box{
    width: 200px;
    height: 300px;
    background-color: orange;
    background-image: -webkit-linear-gradient(top, crimson 0%, transparent 100%);
    transition: all 1s ease-in-out;
}

#box:hover{
    background-color: crimson;
}
<div id="box"></div>


1
你是否总是使用驼峰命名法来编写所有内容? - Bruno
@ibiza 是的。几乎总是。 - hmak.me

0
一种可能性是设置一个渐变,它有两个部分,一个部分颜色会改变,另一个部分颜色保持不变。
并使用 background-image.position 改变你正在展示的渐变部分。

.test {
  width: 300px;
  height: 100px;
  background-image: linear-gradient(to right, rgba(0,0,0,0.65) 50%, rgba(0,0,0,0.3));
  background-size: 200% 100%;
  background-position: 100% 0%;
  transition: background-position 1s;
  margin: 10px;

}

.test:hover {
  background-position: 0% 0%;
}

#test2 {
  background-image: linear-gradient(to right, blue 50%, red 100%);
}
<div class="test"></div>
<div class="test" id="test2"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接