首页
学习
活动
专区
圈层
工具
发布

用js写登录框

以下是一个使用 JavaScript 编写的简单登录框示例:

代码语言:txt
复制
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录框</title>
  <style>
    .login-container {
      width: 300px;
      margin: 0 auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    .login-container input {
      width: calc(100% - 22px);
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }

    .login-container button {
      width: 100%;
      padding: 10px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="login-container">
    <h2>登录</h2>
    <form id="loginForm">
      <input type="text" id="username" placeholder="用户名" required>
      <input type="password" id="password" placeholder="密码" required>
      <button type="submit">登录</button>
    </form>
  </div>

  <script>
    document.getElementById('loginForm').addEventListener('submit', function(event) {
      event.preventDefault();
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;

      // 这里可以添加验证用户名和密码的逻辑,例如与后端服务器进行交互验证
      if (username === 'admin' && password === '123456') {
        alert('登录成功!');
      } else {
        alert('用户名或密码错误!');
      }
    });
  </script>
</body>

</html>

基础概念:

  • HTML 用于构建网页的结构。
  • CSS 用于设置网页的样式。
  • JavaScript 用于实现网页的交互功能。

优势:

  • 简单直观,易于理解和实现。
  • 可以灵活地添加更多的功能和验证逻辑。

类型:

  • 基于前端的简单验证。
  • 结合后端进行更复杂和安全的验证。

应用场景:

  • 小型项目的登录页面。
  • 作为学习和练习的示例。

常见问题及解决方法:

  • 如果出现样式错乱,检查 CSS 选择器和属性是否正确。
  • 若登录验证不生效,确保 JavaScript 中的事件监听和处理逻辑正确,以及输入的值获取准确。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券