【发布时间】:2020-05-01 17:27:50
【问题描述】:
我想添加一个类(或直接设置样式)一个元素,该元素仅在购物车为空时包含购物车计数。
下面是我目前使用的代码,效果很好。购物车数量很好,但颜色没有更新。
header.php(在菜单中的购物车图标之后添加购物车计数)
?>
<div class="counter_bubble">
<a href="/cart">
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
</a>
</div>
<?php
functions.php(排队自定义 javascript + 购物车刷新)
// ADD CUSTOM JS FILE FROM CHILD THEME
add_action('wp_enqueue_scripts', 'bubblescript');
function bubblescript() {
wp_enqueue_script( '_tandt-main', get_template_directory_uri() .
'/../Graffont/js/gft-script.js', array("jquery"), $my_js_ver, true );
}
// REFRESH CART FRAGMENTS (ITEM COUNT) SO CORRECT NUMBER IS ALWAYS SHOWN
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_cart_count', 50, 1 );
function refresh_cart_count( $fragments ){
ob_start();
?>
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
<?php
$fragments['#cart-count'] = ob_get_clean();
return $fragments;
}
gft-script.js
jQuery(document).ready(function($) {
function changecartbubble() {
if ($('body').find('#cart-count').length > 0) {
if (parseInt($('#cart-count').html()) > 0) {
// cart has number > 0 so cart has items
//change background class
$('#cart-count').addClass('other-background-of-bubble');
}
else {
// cart has no number so cart has no items
//remove background class
$('#cart-count').removeClass('other-background-of-bubble');
}
}
}
});
style.css - 当前的 CSS
.counter {
background-color: #ff0;
border-radius: 20px;
font-size: 10px;
padding: 0 4px 0 4px;
}
.other-background-of-bubble{
background-color:red!important;
}
【问题讨论】:
标签: php css wordpress woocommerce cart