【问题标题】:Underline from left to right on hover in and out [duplicate]悬停时从左到右下划线[重复]
【发布时间】:2017-03-07 15:28:56
【问题描述】:

通过以下代码,我得到了从左到右的悬停下划线效果。

.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 会向右而不是向左移动吗?

【问题讨论】:

标签: css css-transitions transitions


【解决方案1】:

您可以尝试为宽度而不是右/左属性设置动画。

.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%;
}
&lt;p&gt;hello, link is &lt;a href="#" class="underline"&gt;underline&lt;/a&gt;&lt;/p&gt;

请参阅此小提琴以获取工作示例:https://jsfiddle.net/1gyksyoa/

【讨论】:

  • 好吧,完成了,但我会添加pointer-events: none。否则,在您首先悬停链接,取消悬停它,但在下划线消失之前,您将悬停在下划线的右侧部分时,它可能会变得疯狂。然后下划线将向左移动,因此不再悬停,因此它将向右移动并再次悬停,依此类推。
【解决方案2】:

基于此答案: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 &lt;a href="#" class="expand"&gt;expand&lt;/a&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2014-08-30
    • 2023-02-01
    • 2013-05-26
    • 2013-04-15
    • 2021-01-22
    • 2020-09-10
    相关资源
    最近更新 更多