在鼠标悬停时,将按钮背景从底部到顶部填充,并将文本颜色从底部到顶部填充。

3

我需要创建一个按钮,当悬停时,它不仅要从底部到顶部填充背景颜色,还要从底部到顶部更改文本颜色。

我可以使用这个方法: CSS:悬停时背景从底部到顶部填充:

但它还必须从底部到顶部更改内部文本颜色。

<style>
 a {
            background-image: linear-gradient(to top, yellow 50%, transparent 50%);
            background-size: 100% 200%;
            background-position: top;
            transition: background-position 0.5s ease-in-out; /** I've changed the time for demo purposes **/
            color: black;
        }

        a:hover {
            background-position: bottom;
        }
</style>
 <a href="#">I'm a link</a>
 <a href="#">I'm another link</a>

这是我需要的截图: 这里是截图链接
1个回答

5

考虑为背景添加额外的图层,并使用背景颜色来着色文本。然后只需以相同的方式动画两者即可:

a {
  padding:20px;
  display:inline-block;
  border:1px solid #000;
  position:relative;
  text-decoration:none;
  font-weight:bold;
  font-size:20px;

  background-image: linear-gradient(to top, red 50%, #000 50%);
  
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
}
a:before {
  content:"";
  z-index:-1;
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-image: linear-gradient(to top, yellow 50%, transparent 50%);
}

a,
a:before {   
  background-size: 100% 200%;
  background-position: top;
  transition: background-position 0.5s ease-in-out;
}

a:hover,
a:hover:before{
  background-position: bottom;
}
<a href="#">I'm a link</a>
<a href="#">I'm another link</a>

您也可以将其设置为多个背景,无需额外元素 (在Firefox上不起作用)

a {
  padding:20px;
  display:inline-block;
  border:1px solid #000;
  position:relative;
  text-decoration:none;
  font-weight:bold;
  font-size:20px;

  background-image: 
    linear-gradient(to top, red 50%, #000 50%),
    linear-gradient(to top, yellow 50%, transparent 50%);
  
  -webkit-background-clip: text,padding-box;
  background-clip: text,padding-box;
  -webkit-text-fill-color: transparent;
  color: transparent;  
  background-size: 100% 200%;
  background-position: top;
  transition: background-position 0.5s ease-in-out;
}

a:hover{
  background-position: bottom;
}
<a href="#">I'm a link</a>
<a href="#">I'm another link</a>


演示在Chrome中可以工作,但在Firefox上悬停时,“background-clip:text”似乎无法正常工作。 - Kravimir
@Kravimir,正如我所说的那样,第二个片段在Fiferox上无法工作,这就是为什么我提供了具有两个层的第一段代码的原因。 - Temani Afif

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