在JavaScript中实现密码显示与隐藏的功能,通常涉及到HTML和CSS的配合使用。以下是一个简单的示例,展示了如何实现这一功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Toggle</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="password-container">
<input type="password" id="password" placeholder="Enter your password">
<button id="togglePassword">Show</button>
</div>
<script src="script.js"></script>
</body>
</html>
.password-container {
position: relative;
width: 300px;
}
#password {
width: 100%;
padding: 10px;
font-size: 16px;
}
#togglePassword {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
cursor: pointer;
}
document.addEventListener('DOMContentLoaded', function() {
const passwordInput = document.getElementById('password');
const toggleButton = document.getElementById('togglePassword');
toggleButton.addEventListener('click', function() {
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
toggleButton.textContent = 'Hide';
} else {
passwordInput.type = 'password';
toggleButton.textContent = 'Show';
}
});
});
type
),在password
和text
之间切换。position: absolute;
和transform: translateY(-50%);
可以使按钮垂直居中。DOMContentLoaded
事件。通过这种方式,你可以轻松地在网页上实现密码显示与隐藏的功能,提升用户体验的同时确保安全性。
领取专属 10元无门槛券
手把手带您无忧上云