核心:获取焦点和失去焦点
获取焦点:
ipt.onfocus = function () {
}
失去焦点:
ipt.onblur = function () {
}
CSS样式:
<style>
div {
width: 300px;
height: 50px;
margin-left: 200px;
margin-top: 200px;
padding-left: 100px;
padding-top: 50px;
background-color: #a7cbff;
}
input {
display: inline-block;
color: gainsboro;
}
button {
display: inline-block;
}
</style>
html和js部分:
<body>
<div>
<input type="text" value="iPhone">
<button>搜索</button>
</div>
<script>
var ipt = document.querySelector('input');
//获取焦点
ipt.onfocus = function () {
//鼠标点击输入框时,若有文本就清空
if (this.value !== '') {
this.value = '';
}
//设置输入字体颜色
this.style.color = '#333'
}
//失去焦点
ipt.onblur = function () {
//鼠标点击空白时出现提示文本
if (ipt.value == '') {
ipt.value = 'iPhone';
}
this.style.color = 'gainsboro';
}
</script>
</body>
效果图: