简体   繁体   English

如何使用JavaScript更新文本框的背景颜色?

[英]How to update the background color of a textbox using JavaScript?

I want to make a text box all in javascript no html (so can use it in the console.log), update background color with setInterval. 我想在不使用html的javascript中创建一个文本框(因此可以在console.log中使用它),使用setInterval更新背景色。 How can it be done? 如何做呢?

This is what I got so far, but does not work. 这是我到目前为止所获得的,但是没有用。

var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);
var color;
setInterval(function(){if (x.setAttribute("value",color)===color{document.body.style.backgroundColor=color};},100);

Don't use setInterval to poll the change, instead use the keyup event to detect when the user changes the value: 不要使用setInterval轮询更改,而应使用keyup事件检测用户何时更改值:

var color = '#FFFFFF';
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);

x.onkeyup = function(){
    color = this.value;
    document.body.style.backgroundColor = color;
};

Here is a working example 这是一个有效的例子

Try this solution works with timeinterval 尝试此解决方案与timeinterval一起使用

var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);
var color = '#FFFFFF';
setInterval(function () {
    color = x.value; // you need to get value of color code 
    document.body.style.backgroundColor = color // then it work here
    console.log(color);
}, 100);

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

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