鼠标悬停时文本滑入的CSS效果

4
我希望当鼠标悬停在 "the wolf" 上时,文本 "Along came" 能够滑动显示。 但是,“the wolf”的位置不应改变。 "Along came" 应该从左侧滑入并淡入,以完成这句话。

.main {
  width: 100vw;
  text-align:center;
}

.addText {
  display: none;
  color: rgba(255,255,255,0);
  transition: .5s;
}

.link:hover .addText {
  display: inline;
  color: red;
  transform: translate(-10px, 00%);
}
<div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div>

1个回答

8
这里有一个想法,可以将元素的width:0,这样就不会影响其他元素:

.main {
  text-align:center;
}
.link {
  display:inline-block; 
}
.addText {
  display:inline-block; /* inline-block so we can set a width */
  width:0;
  white-space:nowrap; /* keep text one line */
  direction:rtl; /* change direction so the text overflow on the left */
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(20px); /* put the value you want here */
  pointer-events:none; /* to avoid the hover on the text, remove to see the difference */
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}
<div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div>

如果您只想让文本占据空间,您也可以只进行翻译:

.main {
  text-align:center;
}
.link {
  display:inline-block; 
}
.addText {
  display:inline-block; 
  color: rgba(255,255,255,0);
  transition: .5s;
  transform: translateX(100%);
}

.link:hover .addText {
  color: red;
  transform: translateX(0);
}
<div class="main">
  <div class="link">
      <span class="addText">Along came </span>
      the wolf
  </div>
</div>


也许将 <div class="link"> 设为内联元素,这样整行就不会对悬停产生反应了? - j08691
感谢@TemaniAfif。我们该如何修复这个问题,使得当鼠标悬停在“the wolf”上时才触发鼠标悬停事件?目前它在鼠标悬停在空白区域时也会滑动。 - amars
@amars 我通过将 .links 添加 inline-block 来修复了它。 - Temani Afif
@TemaniAfif 嗨,是的。看到了那个新更新。但在上面的片段中仍然无法工作。当鼠标停留在“Along came”将出现并停止的空区域时,它仍会飞入。我以为可能是这个网站的问题,但在fiddle上也是一样的 https://jsfiddle.net/aLdo4h16/ - amars
@amars 请再检查一下第一个代码片段,我又更新了一下。 - Temani Afif

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