如何在Rails密码输入框中添加眼睛图标实现密码显示与隐藏切换
密码显示隐藏切换实现方案
你现有代码用了Bootstrap的表单类,直接用输入组组件就能快速实现:
1. 替换原Slim模板代码
将原密码字段部分替换为以下结构,在输入框右侧加入切换按钮:
div.form-group.col-md-12 label =t('.password') div.input-group = f.text_field :password, required: true, label: false, type: 'password', placeholder: 'Password', input_html: {autocomplete: "new-password"}, class: 'form-control input-sm form-control-sm' div.input-group-append button.btn.btn-outline-secondary.toggle-password type="button" // Font Awesome图标版本,没有图标库就注释掉i标签,用下面的文字版本即可 i.fa.fa-eye // 文字版本 // span 显示
2. 加入切换功能JS
原生JS实现,不需要引入额外依赖:
document.addEventListener('DOMContentLoaded', function () { const toggleButtons = document.querySelectorAll('.toggle-password'); toggleButtons.forEach(btn => { // 获取当前关联的密码输入框 const pwdInput = btn.closest('.input-group').querySelector('input'); btn.addEventListener('click', function () { // 切换输入框类型 const currentType = pwdInput.getAttribute('type'); const newType = currentType === 'password' ? 'text' : 'password'; pwdInput.setAttribute('type', newType); // 切换按钮显示内容 const icon = btn.querySelector('i'); if (icon) { // 图标版本切换 icon.classList.toggle('fa-eye'); icon.classList.toggle('fa-eye-slash'); } else { // 文字版本切换 btn.querySelector('span').textContent = newType === 'password' ? '显示' : '隐藏'; } }); }); });
3. 可选样式调整
如果按钮和输入框高度不匹配可以加少量CSS调整:
.toggle-password { cursor: pointer; border-left: 0; } .toggle-password:focus { box-shadow: none; }
内容的提问来源于stack exchange,提问作者Riaz Rahman Aranya
相关产品推荐
相关产品推荐

