Home Web Front-end JS Tutorial How to set the text box color to change when input in javascript

How to set the text box color to change when input in javascript

Jun 09, 2021 pm 04:24 PM

In JavaScript, you can use the onfocus event to set the text box to change color when input. You only need to bind the onfocus event to the element, and then use "object.style.background="color value"". The onfocus event occurs when an object gains focus and is typically used in forms.

How to set the text box color to change when input in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Dynamicly set the text box color:

主要是利用javascript中的触发事件onfocus
<script language="javascript" type="text/javascript">
      <!--
         function myFocus(obj,color){

             //判断文本框中的内容是否是默认内容


             if(obj.value=="请输入收件人地址"){
               obj.value="";
             }

             //设置文本框获取焦点时候背景颜色变换
             obj.style.backgroundColor=color;
         }


         function myblur(obj,color){

             //当鼠标离开时候改变文本框背景颜色
             obj.style.background=color;
         }

 

在input标签中

<input type="text" name="username" id="username" onfocus="myFocus(this,&#39;#f4eaf1&#39;)" onblur="myblur(this,&#39;white&#39;)" value="请输入收件人地址"/>

用上述简单方法可以做到文本框背景颜色的变换和提示信息的清除
Copy after login

The onfocus event occurs when the object gets focus. Onfocus is usually used for ,