[英]Changing output text colour when positive / negative
I have a simple bit of jQuery below which is working as expected. 我下面有一个简单的jQuery,它按预期工作。 I would however like to change it so if the number is positive it turns green and if it is negative it turns red.
但是,我想更改它,因此,如果数字为正,它将变为绿色,如果数字为负,则变为红色。 I know the CSS part and so the styling isn't an issue.
我知道CSS部分,因此样式不是问题。 I am just unsure how to add the class depending on the result.
我只是不确定如何根据结果添加类。
<script type="text/javascript">
jQuery(function($) {
$("#cost_price").on("keyup",function() {
var totalcost= $("#_regular_price").val() - $(this).val()
$(".total_cost").html(totalcost);
})
})
</script>
您可以使用三元语句:
totalcost < 0 ? $(".total_cost").addClass("negative") : $(".total_cost").addClass("positive")
It should be as simple as: 它应该很简单:
var $totalCost = $(".total_cost");
if(totalCost < 0) {
$totalCost.removeClass("green").addClass("red");
} else {
$totalCost.removeClass("red").addClass("green");
}
$totalCost.html(totalCost);
you have a .negative class that sets it to red then Javascript applies it or not 您有一个.negative类,将其设置为红色,然后Javascript是否应用
$("#cost_price").on("keyup",function(){
var totalcost= $("#_regular_price").val() - $(this).val()
$(".total_cost").html(totalcost);
if(totalcost < 0) $(this).addClass("negative");
else $(this).removeClass("negative");
});
One approach: 一种方法:
$(".total_cost").html(totalcost).addClass(Math.abs(totalCost) === totalCost ? 'positive' : 'negative');
Simple JS Fiddle demo . 简单的JS Fiddle演示 。
References: 参考文献:
addClass()
. addClass()
。 Math.abs()
. Math.abs()
。 parseFloat()
. parseFloat()
。 if(totalcost >= 0){
if($(".total_cost").hasClass('red')
$(".total_cost").removeClass('red');
if(!$(".total_cost").hasClass('green')
$(".total_cost").addClass('green');
}
else{
if($(".total_cost").hasClass('green')
$(".total_cost").removeClass('green');
if(!$(".total_cost").hasClass('red')
$(".total_cost").addClass('red');
}
one simple way is to use css3's attrib matching, and a tiny bit of js to publish the value property to a real attribute : 一种简单的方法是使用css3的attrib匹配,以及一小部分js将value属性发布为真实属性 :
<style> input[alt^='-'] { color: red; } </style>
<input oninput="this.alt=this.value" />
which shows red if the value starts with "-". 如果值以“-”开头,则显示为红色。 you can use a type=number and min/max attribs to further improve the user interface.
您可以使用type = number和min / max属性来进一步改善用户界面。
tested in chrome, ff, and IE9. 在chrome,ff和IE9中进行了测试。 use onkeyup for IE8 compat.
将onkeyup用于IE8兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.