Javascript之網頁版待辦事項

本文使用原生JS實現站點 http://www.todolist.cn/ 的基本功能。
其中頁面的HTML佈局和CSS樣式取用原站,JS部分爲自己編寫。

效果圖

待辦事項效果圖

完整代碼

HTML、JS部分

<!DOCTYPE html>
<html>
	<head>
		<title>ToDoList—最簡單的待辦事項列表</title>
		<link rel="stylesheet" href="todolist.css">
	</head>
	<body>
		<header>
			<section>
				<form action="javascript: void(0)" id="form">
					<label for="title">ToDoList</label>
					<input type="text" id="title" placeholder="添加ToDo" autocomplete="off"/>
				</form>
			</section>
		</header>
		<section id="section">
			<h2>正在進行 <span id="todocount"></span></h2>
			<ol id="todolist" class="demo-box">
			</ol>
			<h2>已經完成 <span id="donecount"></span></h2>
			<ul id="donelist">
			</ul>
		</section>
		
        <script>
            var title_ele = document.getElementById("title");
            var todolist_ele = document.getElementById("todolist");
            var donelist_ele = document.getElementById("donelist");
			var section_ele = document.getElementById("section");
			
			// 功能1,添加待辦事項
            addEvent(title_ele, "keydown", function(e){
				var keyCode = e.which || e.keyCode;
				var obj = {
					tag_name : "li",
					children : [
							{
								tag_name : "input",
								attributes : {
										type : "checkbox",
										class : "checkbox"
									}
							},
							{
								tag_name : "p",
								content : title_ele.value
							},
							{
								tag_name : "a",
								attributes : {
										href : "javascript:void(0)"
									},
								content : "-"
							}]
				}
				if(keyCode === 13){
					console.log(title_ele.value);
					if(title_ele.value === ""){
						alert("請輸入待辦事項內容,再按Enter確認")
					}else{
						todolist_ele.insertBefore(createEle(obj), todolist_ele.childNodes[0]);
						title_ele.value = "";
					}
				}
			})

			// 功能2,完成待辦事項
			addEvent(todolist_ele, "change", ".checkbox", function(){
				donelist_ele.insertBefore(this.parentNode, donelist_ele.childNodes[0]);
			})

			// 功能3,重置已完成事項
			addEvent(donelist_ele, "change", ".checkbox", function(){
				todolist_ele.insertBefore(this.parentNode, todolist_ele.childNodes[0]);
			})

			// 功能4,刪除事項
			addEvent(section_ele, "click", "a", function(){
				this.parentNode.remove();
			})

			// 功能5,修改事項內容
			addEvent(todolist_ele, "click", "p", function(){
				var insert_html = '<input value="' + this.innerText + '">';
				this.innerHTML = insert_html;
				this.children[0].select();
				addEvent(this.children[0], "blur", function(){
					this.parentNode.innerText = this.value;
				})
				addEvent(this.children[0], "keydown", function(e){
					var keyCode = e.which || e.keyCode;
					if(keyCode === 13){
						this.parentNode.innerText = this.value;
					}
				})
			})


			// 封裝創建元素的函數
			function createEle(obj){
				var node = document.createElement(obj.tag_name);
				if(obj.attributes){
					// 若屬性存在,則遍歷屬性添加給node
					for(var attr in obj.attributes){
						node.setAttribute(attr, obj.attributes[attr]);
					}
				}
				if(obj.content){
					// 若內容存在,則將內容插入節點中
					node.innerText = obj.content;
				}
				if(obj.children && obj.children.length > 0){
					// 若子集存在,則遍歷子集,遞歸調用createEle()
					for(var i = 0; i < obj.children.length; i++){
						node.appendChild(createEle(obj.children[i]));
					}
				}
				return node;
			}


			// 封裝事件委託和事件監聽
			function addEvent(ele, event_type, cb_or_selector, cb){
				// 若傳入的是4個參數且第三個參數是字符串,說明是添加事件委託
				if(arguments.length === 4 && typeof cb_or_selector === "string"){
					// 添加事件委託,獲取事件目標
					ele.addEventListener(event_type, function(evt){
						var e = evt || event;
						var target = e.target || e.srcElement;
						// 根據傳入的字符串判斷選擇器類型
						switch(cb_or_selector.substr(0, 1)){
							case ".":
								var selector_type = "className";
								var selector_name = cb_or_selector.slice(1);
								break;
							case "#":
								var selector_type = "id";
								var selector_name = cb_or_selector.slice(1);
								break;
							default:
								var selector_type = "nodeName";
								var selector_name = cb_or_selector.toUpperCase();
						}
						// 封裝事件冒泡逐層向上查找事件目標
						while(target !== ele){
							// 驗證事件目標
							if(target[selector_type] === selector_name){
								// 使用call改變this指向
								cb.call(target, e);
								break;
							}
							target = target.parentNode;
						}
					})
					// 若邏輯只有兩種,可以使用 return false
					return false;
				}
				// 若傳入三個參數,說明是添加事件監聽
				ele.addEventListener(event_type, cb_or_selector);
			}
        </script>
	</body>
</html>

CSS部分

body {margin:0;padding:0;font-size:16px;background: #CDCDCD;}
header {height:50px;background:#333;background:rgba(47,47,47,0.98);}
section{margin:0 auto;}
label{float:left;width:100px;line-height:50px;color:#DDD;font-size:24px;cursor:pointer;font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;}
header input{float:right;width:60%;height:24px;margin-top:12px;text-indent:10px;border-radius:5px;box-shadow: 0 1px 0 rgba(255,255,255,0.24), 0 1px 6px rgba(0,0,0,0.45) inset;border:none}
input:focus{outline-width:0}
h2{position:relative;}
span{position:absolute;top:2px;right:5px;display:inline-block;padding:0 5px;height:20px;border-radius:20px;background:#E6E6FA;line-height:22px;text-align:center;color:#666;font-size:14px;}
ol,ul{padding:0;list-style:none;}
li input{position:absolute;top:2px;left:10px;width:22px;height:22px;cursor:pointer;}
p{margin: 0;}
li p input{top:3px;left:40px;width:70%;height:20px;line-height:14px;text-indent:5px;font-size:14px;}
li{height:32px;line-height:32px;background: #fff;position:relative;margin-bottom: 10px;
	padding:0 45px;border-radius:3px;border-left: 5px solid #629A9C;box-shadow: 0 1px 2px rgba(0,0,0,0.07);}
ol li{cursor:move;}
ul li{border-left: 5px solid #999;opacity: 0.5;}
li a{position:absolute;top:2px;right:5px;display:inline-block;width:14px;height:12px;border-radius:14px;border:6px double #FFF;background:#CCC;line-height:14px;text-align:center;color:#FFF;font-weight:bold;font-size:14px;cursor:pointer;}
footer{color:#666;font-size:14px;text-align:center;}
footer a{color:#666;text-decoration:none;color:#999;}
@media screen and (max-device-width: 620px) {section{width:96%;padding:0 2%;}}
@media screen and (min-width: 620px) {section{width:600px;padding:0 10px;}}

注意點

案例封裝了兩個功能函數(可以在其他項目中複用):

  1. 創建元素函數。該函數以對象的形式傳入需要創建元素的基本信息,包括元素標籤元素屬性元素內容子元素等,通過遞歸調用,實現批量創建元素,便於渲染到HTML中。
  2. 添加事件函數。該函數將 事件監聽事件委託 兩項功能封裝到一起,給元素添加事件時可以直接調用,保證了代碼結構的清晰明確。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章