Javascript 根据输入的值更改此输入文本的颜色
我有以下输入文本:Javascript 根据输入的值更改此输入文本的颜色,javascript,jquery,Javascript,Jquery,我有以下输入文本: <div class="form-group"> <label for="newPrice">New Price</label> <input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price"> </div> 我希望在用户键入时根据值的不同动态更改输入的边框 该值将是基于先前定
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
我希望在用户键入时根据值的不同动态更改输入的边框
该值将是基于先前定义的金额的百分比,该金额将根据用户添加的值而变化
因此,如果值低于5%,则在5-10%之间为红色,为琥珀色,超过10%为绿色,等等
任何JavaScript高手都知道最好的方法吗?我将介绍两个事件。第一个是输入,但是contenteditable元素不会在IE11上触发输入事件,所以我也会选择带有超时的按键 输入将在用户输入内容并更改值后立即触发。按键将在用户输入某个内容后触发,但就在值更改之前,介于两者之间 通过这种方式,您可以限制所有现代和旧浏览器的使用,因为addEventListener: 使用focusout。未应用代码段内验证 $newPrice .focusoutfunction{ var价格=$this.val; 如果parseIntprice 5&&parseIntprice 10{ $this.removeClass'green'; $this.removeClass'red'; $this.addClass'blue'; } }; 瑞德先生{ 边框:实心2px红色; } 格林先生{ 边框:实心2倍绿色; } 蓝先生{ 边框:纯色2px蓝色; } 新价格
请拿着,环顾四周,通读一遍,特别是努力解决问题。如果你在使用jQuery时遇到了一个特定的问题,请在尝试使用JavaScript代码时发布一个问题,说明什么不起作用,并解释你迄今为止的研究。what is whizzes?@R3tep在本文中是“专家”的俚语。你尝试过什么吗?谢谢你的评论,这真的帮助了我!感谢您抽出时间发表评论
var tim = null;
var el = document.getElementById("newPrice");
el.addEventListener("keypress", function() {
tim = setTimeout(input, 0);
});
el.addEventListener("input", function input() {
clearTimeout(tim);
// do whatever you want with el.value
if (el.value == "BLAH") {
el.style.backgroundColor = "red";
} else if (parseInt(el.value) > 10) {
el.style.backgroundColor = "green";
} else if (parseInt(el.value) < -12) {
el.style.backgroundColor = "whizzeblue";
}
});
<input id="txt" type="number" onkeyup="changeborder(this.id, this.value)" />
<script type="text/javascript">
function changeborder(id, value){
if(value < 5){
document.getElementById(id).style.border = "2px solid red";
}
else if(value > 5 && value < 10 ){
document.getElementById(id).style.border = "2px solid yellow";
}
}
</script>