【问题标题】:Exclude a pseudo-class from transition in CSS从 CSS 中的过渡中排除伪类
【发布时间】:2021-04-23 12:31:06
【问题描述】:

是否可以排除与另一个伪类具有相同属性的伪类被转换? 请查看以下示例代码供您参考:

button {
  height: 50px;
  width: 150px;
  font-size: 20px;
  color: white;
  border: none;
  background-color: blue;
  transition: all 1s ease-in 500ms;
}

button:hover {
  background-color: black;
}

button:focus {
  background-color: green;
}
<button class="transition">Submit</button>

如果我想将转换应用于:hover 伪类而不是:focus 伪类怎么办?

Demo on JSFiddle

【问题讨论】:

    标签: css css-selectors css-transitions


    【解决方案1】:

    您可以在:focus上添加transition: none;

    button {
      height: 50px;
      width: 150px;
      font-size: 20px;
      color: white;
      border: none;
      background-color: blue;
      transition: all 1s ease-in 500ms;
    }
    
    button:hover {
      background-color: black;
    }
    
    button:focus {
      background-color: green;
      transition: none;
    }
    <button class="transition">Submit</button>

    您也可以在:hover 部分中移动transition: all 1s ease-in 500ms;,但您仍然需要:focus 上的transition: none;,因为:focus 仅在您也:hover 时才会发生

    button {
      height: 50px;
      width: 150px;
      font-size: 20px;
      color: white;
      border: none;
      background-color: blue;
    }
    
    button:hover {
      background-color: black;
      transition: all 1s ease-in 500ms;
    }
    
    button:focus {
      background-color: green;
      transition: none;
    }
    <button class="transition">Submit</button>

    【讨论】:

    • 感谢您的解决方案。提供代码 sn-p 的那个工作得非常好。然而,将transition 属性移动到:hover 中会使元素立即过渡出去,这与过渡开始时不同。此外,在一般意义上,我们可以在没有:hover 的元素上使用:focus。另一个解释原因的 SO 线程 - stackoverflow.com/questions/6143782/….
    【解决方案2】:

    尝试将转换属性应用于button:not(:focus)

    button {
      height: 50px;
      width: 150px;
      font-size: 20px;
      color: white;
      border: none;
      background-color: blue;
    }
    
    button:not(:focus) {
      transition: all 1s ease-in 500ms;
    }
    
    button:hover {
      background-color: black;
    }
    
    button:focus {
      background-color: green;
    }
    <button class="transition">Submit</button>

    【讨论】:

    • 如果我的解释正确,button:not(:focus) 将选择button 上除:focus 之外的所有伪类,并将应用写入其块中的相关CSS 属性。假设我有 4 个伪类 - A、B、C、D,其中,我想将转换应用于 A 和 B,但不应用于 B 和 C。如果我有多个伪类,类似的方法是否有效排除过渡?
    • :not() 仅表示“在除此之外的所有情况下”,因此当没有伪类适用时它也可以工作。就您而言,您只需排除您想要排除的内容:button:not(:B):not(:C)
    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 2012-03-19
    • 1970-01-01
    • 2015-10-21
    • 2011-12-10
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多