2014-09-11 27 views
0

我们有一些用户输入的数据和计算后的结果。现在我想要根据用户在计算后获得的值来更改CSS样式。如何根据INPUT值动态改变css风格?

我的HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
    <style type="text/css"> 
    .not_good { solid red; background:#eee;} 
    .good { solid green; background:#C0E9F6;} 
    </style> 
    <script type="text/javascript"> 

    var BuckwheatCa = 4 

    function convcase(word) { 
     document.convert.Ca.value = BuckwheatCa * document.convert.Buckwheat.value 
    }; 
    </script> 
</head> 
<body> 
    <FORM ACTION="#" NAME="convert"> 
     Buckwheat, gramm 
     <INPUT TYPE=TEXT NAME="Buckwheat" 
     ONKEYUP="convcase(document.convert.Buckwheat.value)" > 
     <table> 
      <tr> 
       <td>Ca</td> <td><INPUT TYPE=TEXT NAME="Ca" DISABLED></td> 
      </tr> 
     </table> 
    </FORM> 
</body> 
</html> 

那么有没有一种方法来创建与使用document.convert.Ca.value变量值的女巫将改变文本的CSS样式在if ... else语句的功能< td>如果变量是< 10例如?

+0

你想改变它''​​什么风格? – Manwal 2014-09-11 10:52:57

+0

@Manwal他说他想根据'Ca'中的输入改变'​​'的风格。 – Barmar 2014-09-11 10:54:09

+0

我想在​​钙来改变文字颜色和​​ @Manwal – 2014-09-11 10:55:29

回答

0

您可以通过使用这个普通的JavaScript代码中的

if(value<10){ 
     document.getElementById("sample").style.color="blue"; 
} 

它做,或者你可以使用jQuery做到这一点:

if(value<10){ 
     $("sample").css("color","blue"); 
} 

选什么吸引你。

当然,你必须有ID作为@Barmar中建议:

<td id='sample'>Ca</td> <td><INPUT TYPE=TEXT NAME="Ca" DISABLED></td> 

上面的代码现在改变了Ca风格单独的ID存在于该标签。

而且你可以改变任何CSS属性:http://www.blooberry.com/indexdot/css/propindex/all.htm

+1

你应该提到他需要提供这些元素ID。 – Barmar 2014-09-11 10:57:26

+0

谢谢,我以为他已经有了ids。 – 2014-09-11 11:01:37

+0

非常感谢! @Mkl Rjv – 2014-09-11 11:12:02

0
function convcase(word) { 
document.convert.Ca.value = BuckwheatCa * document.convert.Buckwheat.value 
// now add css comparison 
if(document.convert.Ca.value < 10){ 
    // using jQuery to access the 'td' and set the css on it 
    $('td').css('font-family', 'arial'); 
} else { 
    // whatever you want 
} 
}; 
+0

不错,谢谢:) @Rob Schmuecker – 2014-09-11 11:13:58