首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查一个元素在CSS中是否有另一个元素

检查一个元素在CSS中是否有另一个元素
EN

Stack Overflow用户
提问于 2020-11-12 16:50:43
回答 1查看 42关注 0票数 0

我正在尝试将WooCommerce元素设计为没有填充和右边按钮的流动式“导航条”样式,如下面的屏幕截图:

代码语言:javascript
复制
<div class="woocommerce-message" role="alert">

    <a href="~~~" tabindex="1" class="button wc-forward">Continue shopping</a> 
    “Product” has been added to your cart.  

</div>

这是一种风格:

代码语言:javascript
复制
.woocommerce-message {
  background: transparent !important;
  box-shadow: 0 0 6px #ddd !important;
  border: 2px solid #8fae1b;
  border-radius: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row-reverse;
  padding: 0;
}

.woocommerce-message .button.wc-forward {
  border-radius: 0;
  border-left: 2px solid #8fae1b;
  background: #8fae1b;
  color: #fff;
  transition: 0.2s opacity;
}

但是有时.woocommerce-message没有一个button元素,所以我只剩下零填充和压缩的外观。我找到了CSS选择器:has(),并考虑使用它作为.woocommerce-message:has(button)并从那里应用样式,但目前不支持浏览器。

是否有另一种方法可以根据HTML中是否存在Button来有条件地样式此消息?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-12 17:22:20

使用jQuery (如果可能的话)是解决这个问题的好方法:

HTML (未更改):

代码语言:javascript
复制
<div class="woocommerce-message" role="alert">
    <a href="~~~" tabindex="1" class="button wc-forward">Continue shopping</a> 
    “Product” has been added to your cart.  
</div>

CSS:

代码语言:javascript
复制
.woocommerce-message {
    background: transparent !important;
    box-shadow: 0 0 6px #ddd !important;
    border: 2px solid #8fae1b;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row-reverse;
}

.woocommerce-message .button.wc-forward {
    border-radius: 0;
    border-left: 2px solid #8fae1b;
    background: #8fae1b;
    color: #fff;
    transition: 0.2s opacity;
}

/* Our new class */
.woocommerce-message-with-button {
    padding: 0;
    /* Add here all the CSS that should be applied to the message WITH button children */ 
}

JavaScript (使用jQuery):

代码语言:javascript
复制
if ($(".woocommerce-message").find("button").length) {
    $(".woocommerce-message").addClass("woocommerce-message-with-button");
} else {
    $(".woocommerce-message").removeClass("woocommerce-message-with-button");
}

解释:

如果我们的woocommerce-message元素有button类型的子元素,jQuery将添加类woocommerce-message-with-button并应用所有所需的CSS。如果没有按钮子元素,则删除类(如果存在的话)。例如,当用户向购物车添加一个项目时,您可以运行这个JavaScript。

单击此处可阅读有关addClassremoveClass的信息。

注意使用jQuery元素类选择器“。将样式应用于CSS类的所有元素。详细信息https://api.jquery.com/class-selector/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64808174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档