js簡單的留言功能程式碼例項

admin發表於2017-04-16

當然真正具有實用價值的留言板需要通過和資料庫的配合,把留言寫入資料庫,然後再顯示出來。

本章節只是演示一下如何使用純前端實現留言板功能,主要演練一下dom元素的操作。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#box{
  width: 800px;
  margin: 0 auto;
}
textarea{
  width: 800px;
}
#ul1{
  list-style: none;
  position: relative;
}
#li:first-child{
  color: red;
  font-weight: bold;
}
#li{
  border-bottom: 1px dashed #ebebeb;
  margin:10px 0;
  padding:8px 0;
}
#ddd{
  text-decoration: none;
  position: absolute;
  bottom: 0;
  right: 0;
  margin:0 5px;
  display: block;
  cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
  <h3>在下面可以進行留言</h3>
  <textarea name="" id="text"  rows="10"></textarea>
  <input type="button" value="確認釋出" id="btn"/>
  <h3>全部留言</h3>
  <hr/>
</div>
<script>
var box = document.getElementById("box");
var text = document.getElementById("text");
var btn = document.getElementById("btn");
var ul = document.createElement("ul");
ul.id = "ul1";
ul.className = "li1";
var div = document.createElement("div");
var div2 = document.createElement("div2");
var date = new Date();
var year = date.getFullYear();
var yue = date.getMonth() + 1;
var ri = date.getDate();
var week = date.getDay();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var br = document.createElement("br");
btn.onclick = function() {
  //建立時間
  div = document.createTextNode(" " + year + "-" + yue + "-" + ri + "");
  div2 = document.createTextNode(week + " " + hour + ":" + min + ":" + sec);
  var li = document.createElement("li");
  li.id = "li";
  //建立刪除功能
  var oA = document.createElement("a");
  oA.id = "ddd";
  oA.href = "#";
  oA.innerHTML = "刪除";
  oA.className = "del";
  oA.style.display = "block";
 
  //刪除
  oA.onclick = function() {
    ul.removeChild(this.parentNode);
  };
  //新增頭像
  var aImg = document.createElement("img");
  var num = parseInt(Math.random() * 8 + 1);
  aImg.src = "img/face" + num + ".gif";
 
  //解決相容問題
  var ali = ul.children;
  if (ali.length == 0) {
    ul.appendChild(li);
  } else {
    ul.insertBefore(li, ali[0]);
  }
  //新增節點
  box.appendChild(ul);
  var textnode = document.createTextNode(text.value);
 
  li.appendChild(aImg);
  li.appendChild(textnode);
  li.appendChild(oA);
  li.appendChild(div);
  li.appendChild(div2);
}
</script>
</body>
</html>

相關文章