仿淘宝搜索栏
完成效果如下:
默认
获取焦点
改文本后
改文本后获取焦点
//css代码 input { color: #999; } //html代码 <input type="text" value="手机"> //js代码 // 1.获取元素 var text = document.querySelector('input') // 2.注册事件 获得事件焦点 onfocus text.onfocus = function(){ if(this.value === '手机'){ this.value = '' } // 获得焦点需要把文本框里面的文字颜色变黑 this.style.color = "#333" } // 3.注册事件 失去焦点 onblur text.onblur = function() { if(this.value === '') this.value = '手机' // 失去焦点需要把文本框里面的文字颜色变黑 this.style.color = "#999" this.style.border = '2px pink solid' }