您好,我的代码有问题,我想做同样的事情,但使用 12 的倍数而不是数字 12
例如 12 瓶啤酒、24 瓶啤酒等,但不是 13、14 或 15 瓶啤酒。
抱歉,我的英语很不好。
https://bcambre-eshop.webflow.io/test
谢谢
<script>
// Initialize texts
$(".beer-info").hide();
$(".beer-info-alt").hide();
$(".checkout-abs").hide();
// select the target node — here : .cart-list
var target = document.getElementById('target');
// input here your reference value
var targetQty = 12;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
//console.log('cart update');
setTimeout(function(){
var currentQty = $('.w-commerce-commercecartopenlinkcount').text();
var leftQty = targetQty - currentQty ;
// update counter — console.log('cans missing' + ' ' + leftQty);
if ( leftQty <= 0 ) {
$(".beers-left").text(leftQty);
$(".beer-info").hide();
$(".beer-info-alt").show();
$(".checkout-abs").show();
}
else {
$(".beer-info-alt").hide();
$(".checkout-abs").hide();
$(".beer-info").show();
$(".beers-left").text(leftQty);
}
// update progression stackbar — console.log(progressBar);
var progressBar = currentQty / targetQty * 100;
$(".completed-bar").css('width', progressBar + '%');
}, 300);
});
});
// configuration of the observer:
var config = {
attributes: false,
childList: true,
characterData: false
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
</script>
var leftQty = targetQty - (currentQty % targetQuantity);
模数运算符%
将给您当前数量除以目标数量后的余数。然后,您可以从 targetQuantity 中减去该值,以得出一包能容纳多少啤酒。
1 % 12 = 1
12 - 1 = 11 beers remaining in a 12 pack
13 % 12 = 1
12 - 1 = 11 beers remaining in a 24 pack
25 % 12 = 1
12 - 1 = 11 beers remaining in a 36 pack
等等
您可以在进度指示器旁边显示当前的包数量。
var totalPacks = Math.ceil(currentQuantity/targetQuantity)
You have {leftQty} beers of pack {totalPacks}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句