悬停时从左到右显示下划线,移开鼠标时消失。

16

使用以下代码,我可以实现从左到右的悬停下划线效果。

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}
.underline:after {
  content: "";
  position: absolute;
  z-index: -1;
  left: 0;
  right: 100%;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: left right;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}
.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  right: 0;
}
<p>hello, link is <a href="#" class="underline">underline</a>
</p>

当你不在悬停状态时,:after元素会回到左侧的初始状态。是否有任何方法,让:after在离开悬停状态时向右移动,而不是向左移动?


你可以使用jQuery hover函数为锚点标签添加一个类,并在jQuery脚本中定义的类中设置一些样式。 - Babidi
1
你是否在寻找类似于这个的东西 - https://dev59.com/U14b5IYBdhLWcg3w1UzL? - Harry
2个回答

29

你可以尝试动画化宽度而不是右/左属性。

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}
.underline:after {
  content: "";
  position: absolute;
  z-index: -1;
  right: 0;
  width: 0;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}
.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  left: 0;
  right: auto;
  width: 100%;
}
<p>hello, link is <a href="#" class="underline">underline</a></p>

查看此JSFiddle示例以获得工作示例:https://jsfiddle.net/1gyksyoa/


做得很好,但我会添加 pointer-events: none。否则,在竞争条件下,您首先悬停链接,取消悬停,但在下划线消失之前,您悬停下划线的右侧部分。然后,下划线将向左移动,因此不再悬停,因此它将向右移动并再次悬停,如此循环。 - Oriol

14

根据这个答案:Expand bottom border on hover,你可以在悬停时更改transform-origin属性,以达到你所需要的“悬停效果”。以下是一个示例:

.expand{
  position:relative;
  text-decoration:none;
  display:inline-block;
}
.expand:after {
  display:block;
  content: '';
  border-bottom: solid 3px #000;  
  transform: scaleX(0);  
  transition: transform 250ms ease-in-out;
  transform-origin:100% 50%
}
.expand:hover:after { 
  transform: scaleX(1);
  transform-origin:0 50%;
}
Here is some dummy text <a href="#" class="expand">expand</a>


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