【问题标题】:Mouseover on div won't change color鼠标悬停在 div 上不会改变颜色
【发布时间】:2015-08-31 20:10:00
【问题描述】:

我正在处理此网站,但无法更改鼠标悬停时的菜单按钮。 我目前有这个 div 我想将鼠标悬停在:

<a href="/index.html"><div class="e" id="menu-button"><p id="menu-text">Home</p></div></a>

类 e 和 ID 绑定到这个 css:

#menu-button {
   background-color: azure;
     color: black;
    height: 3.5vw;
    width: 23%;
    margin-left: 2%;
    color: black;
    magin-top: 2%;
    float: left;

}

.e:hover {
    background-color: blue;
}

在“鼠标悬停”或“悬停”事件中,按钮根本不会改变。 提前致谢!

【问题讨论】:

  • 这是由于 CSS 的特殊性而发生的。 id > class

标签: css html


【解决方案1】:

按 ID 选择 div 元素比按类选择 div 元素更具体,因此 .e:hover 样式将被覆盖。只需将您的代码更改为

#menu-button {
  background-color: azure;
  color: black;
  height: 3.5vw;
  width: 23%;
  margin-left: 2%;
  color: black;
  margin-top: 2%;
  float: left;
}

#menu-button:hover {
  background-color: blue;
}   

【讨论】:

    【解决方案2】:

    .e 元素的background#menu-button 元素覆盖。

    使用id 选择器。 id 选择器的优先级高于 class 选择器。因此,这将不允许类选择器覆盖属性。

    #menu-button:hover {
        background: blue;
    }
    

    Demo

    a {
      display: block;
    }
    #menu-button {
      background-color: azure;
      color: black;
      height: 3.5vw;
      width: 23%;
      margin-left: 2%;
      color: black;
      margin-top: 2%;
      float: left;
    }
    #menu-button:hover {
      background: blue;
    }
    <a href="/index.html">
      <div class="e" id="menu-button">
        <p id="menu-text">Home</p>
      </div>
    </a>

    【讨论】:

      【解决方案3】:

      请改用#menu-button:hover。这里的问题是Specificity of CSS。在这些情况下,ID 具有更高的特异性,会覆盖类选择器 :hover 属性。

      特异性值

      #menu-button100

      .e10

      #menu-button {
        background-color: azure;
        color: black;
        height: 3.5vw;
        width: 23%;
        margin-left: 2%;
        color: black;
        magin-top: 2%;
        float: left;
      }
      #menu-button:hover {
        background-color: blue;
      }
      <a href="/index.html">
        <div class="e" id="menu-button">
          <p id="menu-text">Home</p>
        </div>
      </a>

      【讨论】:

        【解决方案4】:

        您的 css 类悬停已被 id 的 css 覆盖。

        #菜单按钮

        尝试在 id 上使用悬停效果

        #menu-button:hover {
            background-color: blue;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-24
          • 2019-02-11
          • 2018-07-15
          • 2014-05-26
          相关资源
          最近更新 更多