CSS: Replacing a text on hover, but smooth transition to the new text does not work?

我与影子孤独终老i 提交于 2019-12-03 22:15:17

Here is a really simple sample

(This fiddle use pseudo elements instead of below inner div's)

div {
    height: 100px;
    width: 100px;
    position: absolute;
    font-size: 40px;
    color: black
}

.new {
    opacity: 0;
}

.old, .new {
    transition: opacity 0.5s linear;
}

.wrap:hover .old {
    opacity: 0;
}
.wrap:hover .new {
    opacity: 1;
}
<div class="wrap">
<div class="new">New</div>
<div class="old">Old</div>
</div>

OK, so first part, you cannot animate the display property, you need a work-around. To do this we fall back to what we can animate, opacity and width/height

For what you are trying to accomplish, I'd use two spans inside the <h1> - one with each text version. Since spans are inline elements we give them display: block so we can control there dimensions more cleanly.

.my_div {
  background-color: red;
  transition: all 500ms ease-in-out;
}
.my_div:hover {
  background-color: green;
}
h1 {
  overflow: hidden;
}
.old-text,
.new-text {
  display: block;
  overflow: hidden;
  transition: all 500ms ease-in-out;
}
.old-text {
  height: auto;
  opacity: 1;
  width: auto;
}
.new-text {
  color: #fff;
  height: 0;
  opacity: 0;
  width: 0;
}
.my_div:hover .old-text {
  height: 0px;
  opacity: 0;
  width: 0px;
}
.my_div:hover .new-text {
  height: auto;
  opacity: 1;
  width: auto;
}
<div class="my_div">
  <h1 class="title">
        <span class="old-text">This is the old text</span>
        <span class="new-text">A wild text appears!</span>
     </h1>
</div>

The question has already been answered, but I think the best approach would be to use a pseudo element. It's very simple and clean. BUT: you lose the transition effect.

.MySpecialTag:before
{
    content: "The old text";
}
.MySpecialTag:hover:before
{
    content: "The new text";
}
<h1 class="MySpecialTag"></h1>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!