首页 > 解决方案 > 用 :hover 和 :hover:after改变内容

问题描述

此代码工作正常:

HTML:

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

CSS:

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

结果: testhello

但是我怎样才能将“测试”转换为“你好”。我尝试下面的代码,但没有附加任何内容:

CSS:

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

预期结果: goodbye

标签: htmlcsshover

解决方案


content只能与::before和一起使用::aftercontent不是元素内的文本。你应该这样使用它:

.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>


推荐阅读