如何在Laravel Breeze中实现密码字段的显示/隐藏功能?
给Laravel Breeze登录页密码字段添加显示/隐藏功能
步骤1:修改登录页面的密码输入区域
打开login.blade.php,找到密码输入框代码,将其包裹在相对定位容器中并添加切换按钮:
<div class="relative mt-1"> <x-text-input id="password" class="block w-full pr-10" type="password" name="password" required autocomplete="current-password" /> <button type="button" id="togglePassword" class="absolute inset-y-0 right-0 flex items-center px-3 text-gray-500 hover:text-gray-700 focus:outline-none" > <!-- 默认显示密码可见图标 --> <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path> </svg> </button> </div>
步骤2:添加切换功能的JavaScript
在login.blade.php底部(</x-guest-layout>标签前)插入以下脚本:
<script> const toggleBtn = document.getElementById('togglePassword'); const passwordInput = document.getElementById('password'); toggleBtn.addEventListener('click', () => { // 切换密码输入框的type属性 const currentType = passwordInput.getAttribute('type'); passwordInput.setAttribute('type', currentType === 'password' ? 'text' : 'password'); // 切换按钮图标 const svg = toggleBtn.querySelector('svg'); if (currentType === 'password') { svg.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878l3.29-3.29"></path>'; } else { svg.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>'; } }); </script>
说明
- 无需修改
text-input.blade.php组件,它会自动传递所有属性到底层<input>标签,JS可直接修改其type属性。 - 按钮样式和图标遵循Breeze默认UI风格,若不想用SVG图标,可将按钮内容替换为"显示"/"隐藏"文字。
内容的提问来源于stack exchange,提问作者Gapih
相关产品推荐
相关产品推荐

