我正在尝试创建文本效果,因此当您将鼠标悬停在文本上时,似乎有一块颜色穿过文本。

通过使用:before伪元素来实现颜色填充,我完全遵循了the first example here(对于“ Kukuri”一词)的操作。我有在SCSS中编写的代码:

.text {
  position: relative;

  &:hover {
    &:before {
      width: 100%;
    }
  }

  &:before {
    content: 'HELLO'; // if our text was "HELLO"
    width: 0%;
    position: absolute;
    z-index: 2;
    overflow: hidden;
    color: red;
    transition: width 350ms ease-in-out;
    white-space: nowrap;
    width: 0%;
  }
}


但是,我想知道是否可以以其他方式为:before元素的宽度设置动画吗?因此,一旦它达到100%的宽度并填充了颜色,则左侧开始清空,然后返回到0%填充。

最终目标是将其用于导航菜单。当您将鼠标悬停在菜单项上时,类似这种效果的颜色似乎在菜单项中移动:

javascript - 文本填充效果-模拟通过文本的颜色块-LMLPHP

对于这种情况,将鼠标悬停在“关于”项上会使填充颜色消失,而

尝试的解决方案


我尝试转换:before元素,更改leftright属性,并将transform-origin更改为无效。
我尝试研究mix-blend-mode尝试创建一个可能会为文本添加颜色的矩形蒙版。但是,据我了解,mix-blend-mode仅适用于文本,不适用于具有背景颜色的矩形div。

最佳答案

您可以使用混合模式来达到此效果,这里有一个可能性:

我选择移动伪背景,而不是移动伪本身,这样,当伪位于其他元素上方时,您将不会产生副作用。

另外,对于我来说还不确定是要一张幻灯片还是一张幻灯片。我将其设置为双精度(从黑色到红色再到黑色。您可以更改此值,轻松调整最终背景位置



.demo {
    background-color: yellow;
    margin: 10px;
    display: inline-block;
    font-size: 50px;
    padding: 10px;
    position: relative;
}

.demo:after {
    content: "";
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(to right, transparent 25%, red 25%, red 75%, transparent 75% );
    mix-blend-mode: lighten;
    background-size: 400% 100%;
    transition: background-position 2s linear;
    background-position: 100% 0%;
}

.demo:hover:after {
    background-position: 0% 0%;
}

<div class="demo">TEST1</div>
<div class="demo">TEST2</div>





要将运动更改为垂直,需要更改


梯度方向
哪些图像尺寸过大
悬停时更改的背景位置




.demo {
    background-color: yellow;
    margin: 10px;
    display: inline-block;
    font-size: 50px;
    padding: 10px;
    position: relative;
}

.demo:after {
    content: "";
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(to top, transparent 25%, red 25%, red 75%, transparent 75% );
    mix-blend-mode: lighten;
    background-size: 100% 400%;   /* changed vertical dimension */
    transition: background-position 2s linear;
    background-position: 0% 100%; /* changed 100 position to vertical*/
}

.demo:hover:after {
    background-position: 0% 0%;
}

<div class="demo">TEST1</div>
<div class="demo">TEST2</div>

关于javascript - 文本填充效果-模拟通过文本的颜色块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48135203/

10-14 14:59
查看更多