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

<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>这是一种风格:
.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来有条件地样式此消息?
发布于 2020-11-12 17:22:20
使用jQuery (如果可能的话)是解决这个问题的好方法:
HTML (未更改):
<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:
.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):
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。
单击此处可阅读有关addClass和removeClass的信息。
注意使用jQuery元素类选择器“。将样式应用于CSS类的所有元素。详细信息https://api.jquery.com/class-selector/。
https://stackoverflow.com/questions/64808174
复制相似问题