HTML5 localStorage使用演示代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它利用localStorage实现了本地留言板功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style>
ol li {
list-style: none;
}
.show {
border: 1px solid #CCC;
width: 580px;
height: 1000px;
}
#ms li {
border: 1px solid #CCC;
width: 450px;
height: 100px;
margin-bottom: 10px;
margin-left: 20px;
}
#time {
position: relative;
top: 50px;
left: 200px;
font-size: 15px;
}
.zx {
border-bottom: 1px solid #DBDBDB;
padding-bottom: 10px;
margin-left: 10px;
padding-left: 20px;
width: 540px;
}
.bt {
position: relative;
left: 430px;
margin-bottom: 30px;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oul = document.getElementById('ms');
loadStorage("msg");
reversed();
function saveStorage(id) {
var data = document.getElementById(id).value;
var time = new Date().getTime(); //.toLocaleString();
localStorage.setItem(time, data);
alert("已评论");
loadStorage('msg');
}
function loadStorage(id) {
var result = '<ol id="ms">';
var onum = document.getElementById("num");
onum.innerHTML = localStorage.length;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var values = localStorage.getItem(key);
var date = new Date();
date.setTime(key);
var datestr = date.toLocaleString();
result += '<li>' + values + '<br/><span id="time">发表于 ' + datestr + '</span></li>';
}
result += '</ol><br/>';
var target = document.getElementById(id);
target.innerHTML = result;
}
function clearStorage() {
localStorage.clear();
loadStorage("msg");
}
var obtn = document.getElementById('btn');
obtn.onclick = function() {
saveStorage("memo");
reversed();
}
function reversed() {
var obj = document.getElementById("ms");
var lis = obj.getElementsByTagName("li");
for (var i = lis.length - 1; i > -1; i--) {
obj.appendChild(lis[i]);
}
}
var ops = document.getElementById('pass');
ops.onclick = function() {
alert("确定删除");
clearStorage('msg');
}
}
</script>
</head>
<body>
<div>
<h4><b>评论区:</b></h4>
<textarea id="memo" cols="80" rows="7"></textarea><br />
<div class="bt">
<input type="button" id="btn" value="评论">
<input type="button" id="pass" value="删除所有评论">
</div>
</div>
<div class="show">
<h4 class="zx"><b>最新评论(共<span id="num" style="color:#C03">0</span>条评论):</b></h4>
<div id="msg"></div>
</div>
</body>
</html>

HTML5 localStorage使用演示代码实例,这样的场景在实际项目中还是用的比较多的,关于HTML5 localStorage使用演示代码实例就介绍到这了。

HTML5 localStorage使用演示代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容