1.效果展示
2.代码(有详细注释)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
padding-top: 200px;
/* 设置文本框居中 */
background-color: #f5f5f5;
}
.input_box {
position: relative;
width: 250px;
}
.input_box input {
width: 100%;
padding: 10px;
/* 设置一些输入框的样式 */
border: 1px solid #ccc;
border-radius: 5px;
font-size: 1em;
outline: none;
}
.input_box span {
/* 设置定位来控制span的位置 */
position: absolute;
top: 0;
left: 0;
padding: 10px;
font-size: 1em;
pointer-events: none;
/* 它的作用是指定元素在鼠标事件中应该被忽略 也就是不应该阻止输入框的点击聚焦事件 如果不设置 当我们想点击输入框时会被span阻止 因为span在上层*/
color: #ccc;
transition: all .5s;
/* 添加过渡事件 */
}
/* 添加文本框鼠标聚焦事件 */
.input_box input:focus~span {
color: orange;
/* 这些就是鼠标聚焦之后需要做的一些事情 */
font-size: 0.65em;
transform: translateX(10px) translateY(-7px);
padding: 0 10px;
background-color: #fff;
}
</style>
</head>
<body>
<div class="input_box">
<input type="text">
<span>UserName</span>
</div>
</body>
</html>
有什么疑问的话,可以私信或者留言