简体   繁体   English

根据值更改html 5输出对象的颜色

[英]Change the color of an html 5 output object based on value

I want to change the color of the result of a calculation to red if it is negative. 我想将计算结果的颜色更改为红色(如果为负)。 I tried a style sheet, and putting the output into a javascript call, but it did not seem to work. 我尝试了一个样式表,然后将输出放入javascript调用中,但似乎没有用。 Is there a way to change the color of an html 5 output "o" in the example code below to red if it is negative and green if it is positive? 有没有一种方法可以将下面示例代码中的html 5输出“ o”的颜色更改为红色(如果为负)和绿色(如果为正)?

form oninput="o.value = a.valueAsNumber + b.valueAsNumber" 形式oninput =“ o.value = a.valueAsNumber + b.valueAsNumber”
input name="a" id="a" type="number" step="any" + 输入name =“ a” id =“ a” type =“ number” step =“ any” +
input name="b" id="b" type="number" step="any" = 输入name =“ b” id =“ b” type =“ number” step =“ any” =
output name="o" for="ab"> 输出名称=“ o” for =“ ab”>

/form /形成

Not a big fan of just giving answers when users haven't shown what they've tried first but this was actually a bit fun, I've never seen this type of form before. 当用户没有显示他们首先尝试过的内容时,不只是给出答案的忠实粉丝,但这实际上有点有趣,我以前从未见过这种形式的表单。

Like @feeela said, you can use JS to watch for input changes and validate the output field accordingly. 就像@feeela所说的那样,您可以使用JS监视输入更改并相应地验证输出字段。 I'm using jQuery to do this as such: 我正在使用jQuery这样执行此操作:

$(document).ready(function() {
    $('input').change(
        function()
        {
            $('output').removeAttr('class');
            var sum = parseInt($('output').first().html());
            if (isNaN(sum))
            {
                $('output').addClass('error');
            }
            else if (sum < 0)
            {
                $('output').addClass('negative');
            }
            else if (sum > 0)
            {
                $('output').addClass('positive');
            }
        }
    );
});

Then you can use you style sheet to give the output field a colour depending on its class. 然后,您可以使用样式表根据其类别为输出字段提供颜色。 ​ You can view a demo here: http://jsfiddle.net/S7cVP/ 可以在这里查看演示: http : //jsfiddle.net/S7cVP/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM