首页 > 解决方案 > 使用 Javascript 在悬停项上显示文本

问题描述

当我悬停按钮(“类别”)时,我试图在 textInfo 框中显示文本(“innerText”)。有人知道如何解决吗?我想只有 CSS 是不够的,所以需要一些 Javascript。

更新:现在我又增加了一项。但是当我将这些项目悬停时,这两个文本现在都会显示。那么如何才能只显示属于每个单独项目的文本呢?;)

.textInfo {
  border: solid 1px lightblue;
}

.textInfo:hover {
  background-color: #e8a4c9;
  color: #fff;
}

#pastries:hover + #textInfo .innerText-cupCake {
  display: block;
}

#pastries:hover + #textInfo .innerText-cheeseCake {
  display: block;
}

.innerText-cupCake {
  display: none;
}

.innerText-cheeseCake {
  display: none;
}

.item {
  background-color: lightblue;
  width: 200px;
  padding: 5px;
  text-align: center;
}

.item:hover {
  background-color: #e8a4c9;
}

h2 {
  color: #fff;
  font-family: 'Roboto', sans-serif;
  font-weight: 700;
  padding: 10px;
}
<div class="wrapper">
   <div class="box pastries" id="pastries">
     <div class="box item cupcake">Cupcake</div>
     <div class="box item cheesecake">Cheesecake</div>
   </div>
   <div class="box textInfo" id="textInfo">
     <h2>Please, select a category first!</h2>
     <div class="innerText-cupCake">
        <p>Ice cream fruitcake cotton candy.</p>
     </div>
     <div class="innerText-cheeseCake">
        <p>Chocolate sweet roll chupa chups bonbon macaroon.</p>
     </div>
   </div>
 </div>

标签: javascripthtmlcss

解决方案


https://jsfiddle.net/4ucnxsaw/

您需要稍微修改一下html。

 <div class="wrapper">
   <div class="box pastries">
     <div class="box item cupcake">Category
       <div class="innerText">
        <p>Ice cream fruitcake cotton candy.</p>
       </div>
     </div>

   </div>
   <div class="box textInfo"><h2>Please, select a category first!</h2>       
   </div>
 </div>

现在通过 CSS 实现事情将很容易。只需添加样式规则

.item:hover .innerText {
  display: block;
}

推荐阅读