用:hover和:hover:after改变<span>的内容

时间:2019-08-04 20:45:11

标签: html css hover

此代码可以正常工作:

HTML:

<span class="counter" >test</span>

CSS:

  .counter:hover:after{
    content: "hello";
  }

结果: testhello

但是我如何才能将“测试”转换为“你好”。我尝试下面的代码,但没有追加:

CSS:

  .counter:hover{
    content: "goodbye";
  }

预期结果: goodbye

2 个答案:

答案 0 :(得分:2)

content只能与::before::after结合使用。 content不是元素内的文本。您应该以这种方式使用它:

.counter:after {
  content: "hello";
}

.counter:hover::after {
  content: "goodbye";
}
<span class="counter" ></span>

JavaScript解决方案:

const counter = document.querySelector(".counter");

counter.addEventListener("mouseover",function(){
  this.innerHTML = "hello";
})
counter.addEventListener("mouseout",function(){
  this.innerHTML = "goodbye";
})
<span class="counter" >test</span>

答案 1 :(得分:0)

使用font-size隐藏旧内容并显示新内容:

.counter:hover:after {
  content: "hello";
  font-size:initial;
}

.counter:hover {
  font-size:0;
}
<span class="counter">test</span>