如何在背景颜色穿过文本时为文本颜色设置动画

时间:2019-04-18 21:44:58

标签: html css

我有一些带有动画背景的文本,基本上只是一种单色,在悬停时从上到下填充。我希望文本随着背景越过文本而改变颜色。因此,如果要在文本甚至字母中间停顿一下,则文本的一部分将是一种颜色,而文本的其余部分将是另一种颜色。我知道我已经在某处看到了此操作,但现在找不到任何示例。

在下面的gif中,我的文字只是在颜色之间转换,但这并不是我想要的效果。

hover example

2 个答案:

答案 0 :(得分:1)

我要做的是使用伪元素(例如“ :: before”)复制文本并使用不同的颜色和背景,将其绝对定位在另一个之上,然后转换剪切路径(以及用于IE和Safari支持的剪辑。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.example {
    color: #115;
    background: #fff;
    font-size: 2.5em;
    padding: .25em;
    position: relative;
}
.example:hover,
.example:focus {
    /* this empty rule is a fix for IE10 */
}
.example::before {
    content: attr(data-text);
    color: #fff;
    background: #115;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: .25em;
    clip: rect(0,0,2em,0);
    clip-path: inset(0 100% 0 0);
    -moz-transition: clip .5s;
    -webkit-transition: clip .5s;
    transition: clip-path .5s, clip .5s;
}
.example:hover::before,
.example:focus::before {
    clip: rect(0,1920px,2em,0); /* for old browsers that don't support viewport units */
    clip: rect(0,100vw,2em,0); /* can't transition this if 'auto' is specified for any edge */
    clip-path: inset(0);
}
</style>
</head>
<body>

<h2 class="example" data-text="Example">Example</h2>

</body>
</html>

答案 1 :(得分:0)

我有这样的东西,希望对您有所帮助:

button {
  text-align: left;
  position: relative;
  height: 45px;
  width: 100%;
  padding: 5px 5px 5px 15px;
  font-weight: 700;
  font-size: 15px;
  letter-spacing: 2px;
  color: #383736;
  border: 2px #383736 solid;
  text-transform: uppercase;
  outline: 0;
  overflow: hidden;
  background: none;
  z-index: 1;
  cursor: pointer;
  transition: 0.08s ease-in;
  transform: rotate(90deg);
  transform-origin: 20px 20px;
  transition-delay: 0.48s;
}

.btn-fill:hover {
  transition: 0.5s linear all;
  color: white;
}

.btn-fill::before,
.btn-fill::after,
.btn-fill span::before,
.btn-fill span::after {
  content: "";
  position: absolute;
  z-index: -2;
  background: #383736;
  transition: all 1s;
}

.btn-fill:hover::before,
.btn-fill:hover::after,
.btn-fill:hover span::before,
.btn-fill:hover span::after {
  transition: all 1s;
}

.btn-fill-ltr::before {
  top: 0;
  left: 0;
  height: 100%;
  width: 0%;
}

.btn-fill-ltr:hover::before {
  width: 100%;
}
<button class="fill btn-fill btn-fill-ltr">About</button>

基于Jamie Boelman的工作。

Codepen:https://codepen.io/boelmanj/pen/KVveKV