【HTML】利用localstrange临时存储数据

前言

参考资料:

通过本地存储(Local Storage),web 应用程序能够在用户浏览器中对数据进行本地的存储。

在 HTML5 之前,应用程序数据只能存储在 cookie 中,包括每个服务器请求。本地存储则更安全,并且可在不影响网站性能的前提下将大量数据存储于本地。

与 cookie 不同,存储限制要大得多(至少5MB),并且信息不会被传输到服务器。

本地存储经由起源地(origin)(经由域和协议)。所有页面,从起源地,能够存储和访问相同的数据。

注意:localstrange里的数据不是永久保存的,它可能会在浏览器自动清理或手动删除后消失。

例子

Example:登录界面

项目说明

利用localstrange做一个登录、注册页面,可以立即注册和登录。

项目图片

如果你有服务器,将数据存储在服务器上是不二之选。但是没有服务器,我们也可以通过一下方法完成此操作。

思路

  1. 确定临时变量:登录、注册的账号密码,状态

  2. 明确如何调用。

由于存储变量的单一,重复注册会覆盖之前的数据。

过程

登录:

  1. HTML样式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
.container {
width: 300px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
label {
font-weight: bold;
}
input[type="text"],
input[type="password"],
button {
width: 100%;
margin-bottom: 10px;
padding: 8px;
box-sizing: border-box;
}
button {
background-color: #4caf50;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>

<div class="container">
<h2>Login</h2>
<form id="loginForm">
<label for="loginUsername">Username:</label>
<input type="text" id="loginUsername" name="loginUsername" required><br>
<label for="loginPassword">Password:</label>
<input type="password" id="loginPassword" name="loginPassword" required><br><br>
<button type="button" onclick="login()">Login</button>
<button type="button" onclick="window.location.href = 'reg.html';">Register</button>
</form>
</div>
</body>
</html>
  1. 定义(