今天登录掘金的时候,发现输入手机号和密码的时候,上面的小熊是会有不会形态的。于是登录上掘金的第一件事情就是把这个小案例写了下。我是用的最简单的方法来写的。有更加简洁的方法可以在下面评论出来,大家一起进步。
1. 知识点汇总
1.1 结构
- input框的placeholder是作为默认提示的
1.2 样式
- 熊猫定位在盒子上方 定位官方文档学习
1.3 JS交互
思路:
- 当手机号的input框获取到焦点的时候,让‘举手’的熊猫显示;
- 当密码的input获取焦点的时候,让‘闭眼’的熊猫显示;
- 当input框都失去焦点的时候让‘趴着’熊猫显示;
如何实现图片的显示:
我们在写CSS样式的时候,让图片默认是display:none
隐藏。给图片加一个类名,在这个类名下加上display:block
显示的样式。这样后期想让谁显示就直接让他加上这个类名即可。
使用JS获取到的input和img的索引问题:
- ‘趴着’的图片索引是‘0’
- 手机号的input索引是0 ---- ‘举手’的图片索引是‘1’
- 密码的input索引是1 ---- ‘闭眼’的图片索引是‘2’
2. 代码实现
需求:熊猫的状态改变
- 当输入手机号的时候熊猫的状态是‘举手’;
- 当输入密码的时候,熊猫的状态是‘闭眼’;
- 在其他状态熊猫都是‘趴着’
2.1 结构
<form>
<div class='imageBox'>
<img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/v3/static/img/normal.0447fe9.png~tplv-t2oaga2asx-image.image" alt="" class='active'>
<img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/v3/static/img/greeting.1415c1c.png~tplv-t2oaga2asx-image.image" alt="">
<img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/v3/static/img/blindfold.58ce423.png~tplv-t2oaga2asx-image.image" alt="">
</div>
<div class="ipt">
<input type="text" placeholder="输入手机号">
<input type="password" placeholder="输入密码">
</div>
</form>
2.2 样式
* {
margin: 0;
padding: 0;
}
form {
width: 300px;
margin: 100px auto;
border: 1px solid #d6d7d5;
box-sizing: border-box;
text-align: center;
position: relative;
padding: 20px 0;
}
form .imageBox img {
display: none;
width: 100px;
height: 100px;
position: absolute;
top:-76px;
left:91px;
}
form .imageBox img.active {
display: block;
}
form .ipt input {
font-size: 15px;
margin-bottom: 20px;
border: 1px solid #eee;
padding: 5px;
color: #333;
}
form .ipt input:nth-child(2){
margin-bottom: 0;
}
2.3 JS交互
let imageBoxs = document.querySelectorAll('img'),
ipts = document.querySelectorAll('input');
for (let j = 0; j < ipts.length; j++) {
ipts[j].onfocus = function () { //获取焦点做的事情
get(j+ 1); //索引对应相应的图片
};
ipts[j].onblur = function () { //失去焦点做的事情
clear();
}
}
function get(index) {
for (let i = 0; i < imageBoxs.length; i++) {
imageBoxs[i].className = ''; //先清除所有的类名
}
imageBoxs[index].className = 'active'; //为相应的图片加上类名
}
function clear(index) {
for (let i = 0; i < imageBoxs.length; i++) {
imageBoxs[i].className = ''; //清除所有类名
}
imageBoxs[0].className = 'active'; //让‘趴着’熊猫加类名
}
3. 实现效果
4. 总结
这个案例其实就是对JS中函数、input事件的一个简单应用,没有什么难度,但是最重要的是编程思想的养成,善于总结我们写过的每一个案例。加油!