获得焦点时改变文本框的背景和文字颜色,失去焦点时文本框的背景和文字颜色随机改变
onfocus获取焦点
onblur 失去焦点
<input type="text" value="根据焦点操作">
<style>
input {
width: 400px;
height: 40px;
line-height: 40px;
border: 1px solid #ddd;
border-radius: 6px;
display: block;
margin: 40px auto;
padding: 0 10px;
outline: none
}
</style>
window.onload = function () {
var inputs = document.querySelector("input");
inputs.onfocus = function () {
this.style.backgroundColor = "#ccc";
this.style.color = "#666";
};
inputs.onblur = function () {
//Math.random()生成随机数
//Math.floor()取整
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var r1 = Math.floor(Math.random() * 256);
var g1 = Math.floor(Math.random() * 256);
var b1 = Math.floor(Math.random() * 256);
this.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
this.style.color = 'rgb(' + r1 + ',' + g1 + ',' + b1 + ')';
}
}