.wrap {
margin: 0 auto;
width:400px;
padding: 20px;
border: 1px solid red;
}
.user, .pass {
height: 46px;
border: 1px solid #d9d9d9;
padding-left: 48px;
line-height: 46px;
position: relative;
}
.user {
margin-bottom: 10px;
background: url("../images/user.png") 0 0 no-repeat;
}
.pass {
background: url("../images/pass.png") 0 0 no-repeat;
}
.wrap label, .wrap input {
position: absolute;
top: 0px;
left: 48px;
}
.wrap input {
width: 320px;
height: 95%;
line-height: 46px;
background: transparent;
border: none;
outline: none;
}
.wrap label {
width: 320px;
height: 95%;
line-height: 46px;
z-index: 1;
background: transparent;
}
<form class="wrap" action="">
<div class="user">
<label id="userLabel" for="username">请输入用户名</label>
<input type="text" name="username" id="username"/>
</div>
<div class="pass">
<label id="passLabel" for="password">请输入密码</label>
<input type="password" name="password" id="password"/>
</div>
</form>
<script>
var userText = document.getElementById("username");
var userLabel = document.getElementById("userLabel");
var passText = document.getElementById("password");
var passLabel = document.getElementById("passLabel");
userText.onkeyup = function () {
changeLabel(this, userLabel);
};
passText.onkeyup = function () {
changeLabel(this, passLabel);
}
function changeLabel(ele, labelEle) {
var val = ele.value.split(" ").join("");
if (val == "") {
labelEle.style.display = "block";
ele.value = "";
} else {
labelEle.style.display="none";
}
}
</script>