我们模仿一下世纪佳缘网的例子:
当鼠标点击对话框的时候里面的内容隐层,并且对话框变成粉色,点击空白区域,对话框的内容又显示,并且对话框颜色又重新变成黑色。
具体代码如下:
<style>
.box{
width: 600px;
padding-left: 500px;
}
input{
color: #999;
border-color: #999;
}
button{
background-color: #317ef3;
}
</style>
<div class="box">
<input class="ipt1" type="text" value="邮箱/ID/手机号">
<input class="ipt2" type="text" value="密码">
<button>登录</button>
</div>
<script>
var ipt1=document.querySelector('.ipt1');
var ipt2=document.querySelector('.ipt2');
ipt1.onfocus=function () {
if (this.value === '邮箱/ID/手机号') {
this.value = '';
}
this.style.color='#333';
this.style.borderColor="pink"
}
ipt1.onblur=function(){
if(this.value===''){
this.value='邮箱/ID/手机号';
}
this.style.color='#999';
this.style.borderColor="#999"
}
ipt2.onfocus=function () {
if (this.value === '密码') {
this.value = '';
this.type='password';
}
this.style.color='#333';
this.style.borderColor="pink"
}
ipt2.onblur=function(){
if(this.value===''){
this.value='密码';
this.type='text';
}
this.style.color='#999';
this.style.borderColor="#999"
}
</script>
结果如下图:
接着讲一下大概的思路和代码的大致意思:
首先我们要见一个div盒子,然后放入两个输入和登录按钮,用css要调整合适的样式位置。
然后在js中分别获取两个输入框的事件源。
用onfocus来获取事件的焦点,当点击输入框时,判断输入框的内容,如果输入框的内容与原内容一样,则更改输入框的值为空字符串,以达到隐层的效果。同时修改输入框的颜色(this.style.borderColor=“pink”)。
用onblur来失去焦点,从而达到显示输入框内容的效果,思路与获取焦点的思路一样(只是结果相反而已)。