【问题标题】:How to avoid hover styles when using only-child使用独生子女时如何避免悬停样式
【发布时间】:2018-07-01 23:21:12
【问题描述】:

我正在使用唯一子选择器来显示特定的背景颜色,并使用悬停样式来显示不同的背景颜色。问题是当只有一个孩子时,我不希望悬停样式起作用。我该怎么做?

1) 没有红色背景,但是当我们悬停时它会变成绿色背景

.report p:only-child {
  background: red;
}

.report p:hover {
  background: green;
}
<div class="report">
  <p>Test1</p>
  <p>Test2</p>
</div>

2) 悬停时红色背景,但没有绿色背景

.report p:only-child {
  background: red;
}

.report p:hover {
  background: green;
}
<div class="report">
  <p>Test1</p>
</div>

【问题讨论】:

    标签: javascript html css hover


    【解决方案1】:

    简单,只需将你已有的两个伪类结合起来即可:)

    .report p:only-child,
    .report p:only-child:hover{
        background: red;
    }
    .report p:hover{
        background: green;
    }
    

    这是一个小提琴:https://jsfiddle.net/5ccjphjj/

    【讨论】:

      【解决方案2】:

      更新您的选择器以额外使用以下非选择器

      .report p:not(:only-child):hover{
          background: green;
      }
      

      【讨论】:

      • 我选择了这个答案,因为它已经出现了
      【解决方案3】:

      试试.report p:not(:only-child):hover

      堆栈片段

      .report p:only-child {
        background: red;
      }
      
      .report p:not(:only-child):hover {
        background: green;
      }
      <div class="report">
        <p>Test1</p>
      </div>
      
      <div class="report">
        <p>Test1</p>
        <p>Test1</p>
      </div>

      【讨论】:

      • 没有投反对票,但原因可能是因为您的答案是现有旧答案的精确副本
      猜你喜欢
      • 1970-01-01
      • 2013-03-25
      • 2017-09-30
      • 2018-10-20
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2018-07-28
      • 2011-01-31
      相关资源
      最近更新 更多