我想写一些代码,当没有任何东西(0)被添加到购物车时,图标是浅灰色,但当某些东西被添加到购物车时,它会变为红色。
<span class="cart-item-number">1</span>
如果购物车大于或等于1,我该如何更改颜色?我会用JQuery或PHP来做这件事吗?
答案 0 :(得分:0)
我建议jquery根据值更改颜色。
span
默认情况下没有change
触发器。因此,当您向购物车添加内容时,您需要手动触发change
,如下所示:
$('span').text(v).trigger('change');
然后你可以听change
触发器并做你想做的事情:
$('span').on('change', function() {
var v = parseInt($('span').text());
if (v > 0) {
$('span').css('background', 'red');
}else{
$('span').css('background', 'gray');
}
});
答案 1 :(得分:0)
您可以使用input
事件:
$(document).ready(function() {
$(".cart-item-number").on("input",function(){
$value = parseFloat($(this).text());
if ($value > 0)
$(this).css({backgroundColor:"red"});
else
$(this).css({backgroundColor:"gray"});
})
})
最终代码:
<!DOCTYPE html>
<html>
<head>
<style>
.cart-item-number {
width: 50px;
height: 20px;
border: 2px solid #000;
display: inline-block;
background-color: red;
}
</style>
</head>
<body>
<span class="cart-item-number" contenteditable="true">1</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".cart-item-number").on("input",function(){
$value = parseFloat($(this).text());
if ($value > 0 )
$(this).css({backgroundColor:"red"});
else
$(this).css({backgroundColor:"gray"});
})
})
</script>
</body>
</html>