input输入密码类型,点击小眼睛显示密码或隐藏功能
时间: 2023-12-16 16:02:59 浏览: 68
是的,你可以使用JavaScript和CSS来实现一个可以切换密码可见性的功能。
首先,我们需要在HTML中添加一个input元素和一个小眼睛图标的按钮。在input元素中设置type为password,这会将input元素转换为密码输入框。
```html
<div class="input-group">
<input type="password" class="form-control" id="password-input" placeholder="Password">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="toggle-password">
<i class="fa fa-eye-slash"></i>
</button>
</div>
</div>
```
接下来,我们需要使用JavaScript来监听按钮的点击事件。当按钮被点击时,我们需要切换input元素的type属性,并根据type属性来切换按钮图标的class。
```javascript
const passwordInput = document.querySelector('#password-input');
const togglePasswordButton = document.querySelector('#toggle-password');
togglePasswordButton.addEventListener('click', function (e) {
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
passwordInput.setAttribute('type', type);
this.querySelector('i').classList.toggle('fa-eye');
this.querySelector('i').classList.toggle('fa-eye-slash');
});
```
最后,我们需要添加一些CSS样式来美化我们的密码输入框和按钮。
```css
.input-group {
position: relative;
}
.input-group-append {
position: absolute;
right: 0;
top: 0;
height: 100%;
}
.btn {
border-radius: 0;
}
.form-control {
border-radius: 0;
border-right: none;
}
.btn:focus,
.form-control:focus {
box-shadow: none;
}
.btn i {
font-size: 1.2rem;
}
.fa-eye-slash:before {
content: '\f070';
}
.fa-eye:before {
content: '\f06e';
}
```
这样,我们就实现了一个可以切换密码可见性的功能。