HTML5 localStorage使用演示程式碼例項

admin發表於2017-04-16

分享一段程式碼例項,它利用localStorage實現了本地留言板功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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>

相關文章