赞
踩
设计一个TODO List,页面结构如下图所示,要求:
<h1>todos</h1>
<div class="content">
<div class="box">
<span class="iconfont icon-zhankai" id="hidden"></span>
<input type="text" id="input">
</div>
<div class="box2">
<ul id="list">
<!-- <li class="item"> -->
<!-- <span class="infor">12232</span>
<span class="iconfont icon-fork" id="del"></span> -->
<!-- </li> -->
</ul>
</div>
</div>
样式设计代码如下:
<style> * { margin: 0; padding: 0; list-style: none; } body { background-color: #E8F0DB; } h1 { margin: 20px auto; font-size: 40px; text-align: center; color: #FF6600; } .content { width: 300px; height: 300px; margin: auto; } .box { width: 100%; height: 30px; background-color: #fff; border: 1px solid #FF6600; } .box>span { float: left; margin-left: 5px; font-size: 18px; line-height: 30px; } .box>input { float: right; width: 88%; height: 28px; border: none; outline: none; } .box2 { width: 100%; } .box2>#list>.item { width: 100%; height: 30px; color: snow; background-color: rgba(248, 165, 42, 0.6); border: 1px solid #fff; } .box2>ul>.item>.infor { display: inline; margin-left: 15px; font-size: 18px; line-height: 30px; } .box2>ul>.item>.del { float: right; margin-right: 10px; font-size: 20px; line-height: 30px; user-select: none; } .change { display: none; } </style>
页面主体样式如下图所示:
核心js代码如下:
let oInput = document.getElementById('input'); let oUl = document.getElementById('list'); let oLi = document.getElementsByClassName('item'); let oHidden = document.getElementById('hidden'); //添加键盘按下时间 document.onkeydown = function (ev) { ev = ev || window.event; if (ev.keyCode === 13) { let value = oInput.value; //不输入内容的时候弹出提示框 if (value === '') { alert('请输入内容'); } else { //生成li标签以及li里的两个标签 let li = document.createElement('li'); let p = document.createElement('p'); let span = document.createElement('span'); //给标签设置类名 li.className = "item" p.className = "infor" span.className = "del" //向标签中添加内容 p.innerHTML = value; span.innerHTML = "x" //向li中渲染 li.appendChild(p); li.appendChild(span); //给ul中渲染内容 oUl.appendChild(li); //设置输入框清空 oInput.value = ''; //点击x号删除 span.onclick = function () { oUl.removeChild(this.parentNode) } //点击展开按钮展开或隐藏 oHidden.onclick = function () { oUl.classList.toggle('change'); } } } } //模糊查询 function select() { oInput.addEventListener('keyup', function (e) { //监听键盘抬起事件(所有键盘按钮) let str = e.target.value; let reg = new RegExp('(' + str + ')', 'g'); //匹配到的文字变红色,准备工作 for (var i = 0; i < oLi.length; i++) { let one = oLi[i].getElementsByTagName('p')[0]; let newStr = one.innerText.replace(reg, '<font color=red>$1</font>');//换-->红色,用innerText防止用innerHTML将标签也读取出来出错。 if (one.innerText.indexOf(str) !== -1) { //也选用innerHTML one.innerHTML = newStr; //匹配到的变红 } } }); } select(); //函数解析完就运行
效果展示如下图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。