題目:
html
題目來源:連接前端
思路:node
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>頭條前端最後一道題</title> <style> .main-header { text-align: center; } h1 { font-size: 100px; color: rgba(175, 47, 47, 0.4); font-weight: 100; margin: 20px; } .real-app { width:600px; margin: 0 auto; box-shadow: 0 0 5px #666; } .add-input { position: relative; margin: 0; width: 100%; font-size: 24px; font-family: inherit; font-weight: inherit; line-height: 1.4em; border: 0; outline: none; color: inherit; padding: 6px; border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); box-sizing: border-box; font-smoothing: antialiased; padding: 16px 16px 16px 60px; border: none; box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03); } li { margin: 4px 0; color: rgba(175, 47, 47, 0.8); list-style: none; padding-left: 18px; } .close{ width: 20px; height: 20px; float:right; background: rgba(0,0,0,0.2); text-align: center; line-height: 20px; position: relative; bottom: 3px; right:4px; } </style> </head> <body> <div class="main-header"> <h1>todos</h1> </div> <div class="real-app"> <input type="text" class="add-input" placeholder="請在這裏輸入"> <ul id="parent"> </ul> </div> </body> <script> var arr = []; var button = "<div class='close'>X</div>"; // var button = " X"; var input = document.getElementsByClassName("add-input")[0]; var left = input.offsetLeft; document.getElementById("parent").addEventListener("click",function(e) { // e.target是被點擊的元素!,this是在父元素捕獲的ul // 若是被點擊的是li元素 // console.log("success"); if(e.target && e.target.nodeName == "DIV") { // console.log(this); // console.log(e.target); // console.log(e.target.parentNode) var str = e.target.parentNode.innerHTML.toString(); var k = str.indexOf("<"); str = str.substr(0,k); // console.log(str); e.target.parentNode.parentNode.removeChild(e.target.parentNode); arr.pop(str); // arr.pop(e.target.parentNode.text) } }); //onkeyup 屬性在用戶(在鍵盤上)釋放按鍵時觸發。 /* 提示:相對於 onkeyup 事件的事件次序: onkeydown onkeypress onkeyup onkey是鍵盤接受字符後的事件,這點和onkeypress不一樣 */ input.onkeyup = function(e) { var value = this.value; console.log(value); var ul = document.getElementsByTagName('ul')[0]; ul.style.left = left + "px"; ul.style.border = "none"; ul.innerHTML = ""; if(value) { var reg = new RegExp(value); for(var i = 0; i <arr.length; i++ ) { //string類型的match方法 if(arr[i].match(reg)) { var li = document.createElement('li'); li.innerHTML = arr[i] + button; ul.style.border = "1px solid black"; ul.appendChild(li); } } e = e || window.event; if(e.keyCode == 13) { var newLi = document.createElement('li'); var newValue = value; newLi.innerHTML = newValue + button; ul.appendChild(newLi); arr.push(newValue); input.value = ""; } } // 按照這個方法給每一個li添加事件太浪費了,每次新增長回車就要操做一遍,能夠利用時間委託機制,即上面的 // var close = document.getElementsByClassName("close"); // for(var i = 0; i < close.length; i++) { // (function(i){ // close[i].onlick = function(){ // this.parentNode.parentNode.removeChild(this.parentNode); // } // })(i); // } } </script> </html>