悬停时的直线动画

时间:2015-10-02 07:11:01

标签: javascript html css

我想做一些事情,我有一个直通文本,当我将鼠标悬停在文本上时,线条缩回。

这是我到目前为止所做的:



#about {
  text-decoration: line-through;
  text-align: right;
  padding-right: 80px;
  float: right;
  color: black;
}
#about:hover {
  text-decoration: none;
}

<div id="about"><a href="about.html" target="_new">ABOUT</a>
</div>
&#13;
&#13;
&#13;

我该怎么做? CSS还是Javascript?

3 个答案:

答案 0 :(得分:2)

伪元素将是这里的理想选择。

&#13;
&#13;
a {
  display: inline-block;
  text-decoration: none;
  margin: 25px;
  color:black;
  position: relative;
}

a::after {
  content: '';
  position: absolute;
  top:50%;
  transform:translateY(-50%);
  width: 100%;
  right: 0;
  height: 25%;
  background: currentColor;
  transition:width 0.25s ease;
}

a:hover::after {
  width: 0;
}
&#13;
<a href="#">Profile</a>

<a href="#">Lorem ipsum dolor.</a>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

虽然不是text-decoration: line-through;,但这是可能的。我们可以通过使用伪元素并相应地为其设置动画来重现line-through效果。

原则上:

  • position: relative;添加到#about,这样可以使伪元素相对于它定位
  • 创建一个伪元素#about:after,为其提供height: 1px;width: 100%;以复制直通效果
  • 绝对定位伪元素并使用top: 0;bottom: 0;margin: auto 0;垂直对齐
  • 添加transition: width 1s;以设置宽度动画
  • 使用#about:hover:after添加悬停事件并设置width: 0;

&#13;
&#13;
#about {
  color: black;
  position: relative;
  text-decoration: none;
}
#about:after {
  background-color: black;
  bottom: 0;
  content: "";
  display: block;
  height: 1px;
  margin: auto 0;
  position: absolute;
  top: 0;
  transition: width 1s;
  width: 100%;
}
#about:hover:after {
  width: 0;
}
&#13;
<a id="about" href="about.html">ABOUT</a>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

移动text-decoration:line-through不能通过CSS或JS来完成。

但是,您可以使用动画制作的其他元素,例如像这样:

.strike {
    position: relative;
}

.strike:before {
    content:" ";
    position: absolute;
    left: 0;
    top: 50%;
    border-bottom: 1px solid red;
    width: 100%;
    transition: left 2s;
}

.strike:hover:before {
     left: -120%
}

请参阅jsfiddle here