【问题标题】:How to show an image on hover of a div and then on hover of that image change its CSS properties如何在 div 悬停时显示图像,然后在该图像悬停时更改其 CSS 属性
【发布时间】:2021-11-06 22:15:04
【问题描述】:

我正在尝试实现这个:

第 1 部分: 在父 div 悬停时,显示一个透明的信息图标。 (请在附件中找到显示信息图标的图片)。

第 2 部分: 接下来,当父 div 以绿色背景突出显示并且悬停在透明信息图标上时,我需要将其更改为活动信息图标。 (显示鼠标悬停在信息图标上。请看图)。

我能够完成第 1 部分。但是,在第 2 部分中遇到问题,将鼠标悬停在显示的正常信息图标上不会使用我的 CSS 激活活动图标。关于如何实现这一点的任何建议?

这是我到目前为止所尝试的。这是HTML:

<div>
    <div id="parent">
        <span class="hover-text">Some Text to hover</span>
        <div class="info-icon"/>
    </div>
</div>

这是 CSS:

#parent {
  &:hover {
    background-color: #016E69;
  }
 }
 
 #parent:hover .info-icon { 
    display: block;
    cursor: pointer;
    background: url(../assets/info-icon-transparent.png);
  }

.info-icon{
   background: url(../assets/info-icon-transparent.png);
   width: 24px;
   height: 24px;
   float: left;
   margin-top: 6px;
   display: none;
   margin-left: 12px;
}

 .info-icon:hover {
   background: url(../assets/info-icon-active.png);
}

【问题讨论】:

  • 选择器#parent:hover .info-icon.info-icon:hover 具有更高的特异性,因此第一条规则中定义的背景仍然胜出。将第二个更改为#parent .info-icon:hover,然后它们将具有相同的特异性,并且应该可以工作。
  • 或者从#parent:hover .info-icon 规则中删除background - 您已经使用.info-icon 设置它,所以在开始时首先提到的规则是多余的。
  • 感谢 CRroe。尝试了第一个解决方案。成功了!!

标签: html css


【解决方案1】:

阅读https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity,以了解更好的特异性。

根据您编写样式的方式,这是:

#parent:hover .info-icon { 
    display: block;
    cursor: pointer;
    background: url(../assets/info-icon-transparent.png);
}

将优先于你的最后一行

.info-icon:hover {
   background: url(../assets/info-icon-active.png);
}

因此将父悬停更新为此并删除 .info-icon:hover

#parent:hover .info-icon { 
    display: block;
    cursor: pointer;
    background: url(../assets/info-icon-active.png);
}

ps。您的 html 也缺少一个关闭 div,并且还有其他方法可以实现您想要做的事情,例如仅使用字体图标或仅使用 1 个图像并在悬停时更改不透明度。更少的图像,您使用的浏览器需要下载的资源更少,页面加载速度更快;)

【讨论】:

    【解决方案2】:

    @import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css");
    
    button {
      background-color: #016E69;
      color: #fff;
      padding: 5px;
      border: none;
    }
    
    button i.opacity {
      opacity: 0.5;
      transition: all 0.2;
    }
    
    button:hover i.opacity {
      opacity: 1;
    }
    <button>
      <i class="bi bi-arrow-right"></i> Some text to hover <i class="bi bi-info-circle opacity"></i>
    </button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 2021-01-06
      • 2014-04-11
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多