常用的js代码片段
1.单选框/手风琴
1 <script> 2 $(document).ready(function(){ 3 $("dd").on("click",function(){ 4 var $this = $(this); 5 $("dd").removeClass("selected"); 6 $this.addClass("selected"); 7 }) 8 }) 9 </script>
2.复选框
1 function checkListTwo(){ //点击变换效果 2 var li = document.getElementById("checkList").getElementsByTagName("li"); 3 for(var i=0;i<li.length;i++){ 4 li[i].onclick = function(){ 5 if(this.className == 'selected'){ 6 this.className = null; //单击若判断已有类,再次点击选中会清空class 7 }else{ 8 this.className = 'selected'; 9 } 10 } 11 } 12 }
3.多级导航菜单
1 <script> 2 window.onload=function(){ 3 var aLi=document.getElementsByTagName('li'); 4 5 for(var i=0; i<aLi.length; i++){ 6 aLi[i].onmouseover=function(){ 7 //鼠标经过一级菜单,二级菜单动画下拉显示出来 8 var subNav=this.getElementsByTagName("ul")[0]; 9 subNav.className=''; 10 //alert(subNav.innerHTML); 11 } 12 //鼠标离开菜单,二级菜单动画收缩起来。 13 aLi[i].onmouseout=function(){ 14 var subNav=this.getElementsByTagName("ul")[0]; 15 subNav.className="subNav"; 16 } 17 } 18 } 19 </script>
4.获取时间,把获取到的毫秒数转换成我们需要的时间格式即可
1 function getFormatTime(time) { 2 var time = time 0; 3 4 var h = parseInt(time/3600), 5 m = parseInt(time%3600/60), 6 s = parseInt(time%60); 7 h = h < 10 ? "0"+h : h; 8 m = m < 10 ? "0"+m : m; 9 s = s < 10 ? "0"+s : s; 10 11 return h+":"+m+":"+s; 12 }
5.小时钟显示
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 6 <title>Date</title> 7 </head> 8 <body onload="startTime()"> 9 <script> 10 // var date = new Date(); 11 // document.write(date.getFullYear()+"<br />");//年 12 // document.write(date.getMonth()+"<br />"); //月要加1 13 // document.write(date.getDate()+"<br />");//日期 14 // document.write(date.getDay()+"<br />"); //星期 15 // document.write(date.getHours()+"<br />");//时 16 // document.write(date.getMinutes()+"<br />");//分 17 // document.write(date.getSeconds()+"<br />"); //秒 18 19 function startTime() { 20 var today = new Date(); 21 var h = today.getHours(); 22 var m = today.getMinutes(); 23 var s = today.getSeconds(); 24 m = checkTime(m); 25 s = checkTime(s); 26 document.getElementById("timetxt").innerHTML = h+":"+m+":"+s; 27 t = setTimeout(function(){ 28 startTime(); 29 },500); 30 } 31 function checkTime(i){ 32 if(i<10){ 33 i = "0"+i; 34 } 35 return i; 36 } 37 </script> 38 <div id="timetxt"></div> 39 </body> 40 </html>
6.小写转大写
1 <html> 2 3 <head> 4 <script type="text/javascript"> 5 function upperCase(x) 6 { 7 var y=document.getElementById(x).value 8 document.getElementById(x).value=y.toUpperCase() 9 } 10 </script> 11 </head> 12 13 <body> 14 15 Enter your name: <input type="text" id="fname" onchange="upperCase(this.id)"> 16 17 </body> 18 </html>
7.禁止用户输入数字
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <form> 9 Type some text (numbers not allowed): 10 <input type="text" onkeydown="return noNumbers(event)" /> 11 </form> 12 13 <script type="text/javascript"> 14 function noNumbers(e) 15 { 16 var keynum; 17 var keychar; 18 var numcheck; 19 20 if(window.event) // IE 21 { 22 keynum = e.keyCode; 23 } 24 else if(e.which) // Netscape/Firefox/Opera 25 { 26 keynum = e.which 27 } 28 keychar = String.fromCharCode(keynum) 29 numcheck = /\d+/ 30 return !numcheck.test(keychar) //把这个!去掉就是不能限制字母了 31 } 32 </script> 33 </body> 34 </html>
8.Web SQL浏览器端数据库
<html> <head> <meta charset="UTF-8"> <title>Web SQL</title> <script type="text/javascript"> var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "lucas")'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.baidu.com")'); msg = '<p>数据表已创建,且插入了两条数据。</p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('DELETE FROM LOGS WHERE id=1'); msg = '<p>删除 id 为 1 的记录。</p>'; document.querySelector('#status').innerHTML += msg; }); db.transaction(function (tx) { tx.executeSql('UPDATE LOGS SET log=\'baidu.com\' WHERE id=2'); msg = '<p>更新 id 为 2 的记录。</p>'; document.querySelector('#status').innerHTML += msg; }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>查询记录条数: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; document.querySelector('#status').innerHTML += msg; } }, null); }); </script> </head> <body> <div id="status" name="status">状态信息</div> </body> </html>
9.一个增删demo
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>一个增删demo</title> 6 </head> 7 <body> 8 <input type="text" id="text"> 9 <input type="button" value="添加" id="button"> 10 <ul> 11 <li>第1个<button class="btn" id="1">删除</button></li> 12 <li>第2个<button class="btn" id="2">删除</button></li> 13 <li>第3个<button class="btn" id="3">删除</button></li> 14 </ul> 15 <script> 16 var button = document.getElementById("button"); 17 var text = document.getElementById("text"); 18 var ul = document.getElementsByTagName("ul")[0]; 19 var btnClass = document.getElementsByClassName("btn"); 20 button.onclick = function(){ 21 var deleteButton = document.createElement("button"); 22 var value = text.value; 23 deleteButton.setAttribute("class","btn"); 24 var deleteText = document.createTextNode("删除"); 25 deleteButton.appendChild(deleteText); 26 var li = document.createElement("li"); 27 var liText = document.createTextNode(value); 28 li.appendChild(liText); 29 li.appendChild(deleteButton); 30 ul.appendChild(li); 31 for(var i=0;i<btnClass.length;i++){ 32 btnClass[i].onclick=function(){ 33 this.parentNode.parentNode.removeChild(this.parentNode); 34 } 35 } 36 } 37 38 for(var i=0;i<btnClass.length;i++){ 39 btnClass[i].onclick=function(){ 40 this.parentNode.parentNode.removeChild(this.parentNode); 41 } 42 } 43 </script> 44 </body> 45 </html>
10.Generator抽奖逻辑
1 <script type="text/javascript"> 2 /*generator实现抽奖逻辑*/ 3 let draw=function(count){ 4 console.info(`剩余${count}`); 5 } 6 let residue=function* (count){ 7 while(count>0){ 8 count--; 9 yield draw(count); 10 } 11 } 12 13 let star=residue(5); //将Generator实例 14 star.next() 15 star.next() 16 star.next() 17 </script>
11.检测数据类型
//写出一个比typeof运算符更准确的类型判断函数。 var type = function (o){ var s = Object.prototype.toString.call(o); return s.match(/\[object (.*?)\]/)[1].toLowerCase(); }; type({}); // "object" type([]); // "array" type(5); // "number" type(null); // "null" type(); // "undefined" type(/abcd/); // "regex" type(new Date()); // "date"
function checkedType(target){ return Object.prototype.toString.call(target).slice(8,-1); }
<script> let str=1234; let str3=str.constructor.toString(); //返回:function Number() { [native code] } alert(str3.slice(9,-20)) </script>
12.数组去重——Array.filter()
let arr=[2,3,4,2,3]; console.log(arr.filter(function(item,index,self){ return self.indexOf(item)==index} ) )
注:性能差
13.数组/字符串去重——利用for循环去重
/*var arr1 ="abcdabcd";*/ var arr1=['a','b','c','a','d','b'] var arr2=[]; for(var i=0;i<arr1.length;i++){ if(arr2.indexOf(arr1[i])<0){ arr2.push(arr1[i]); } } document.write(arr2);
注:性能良好
13.1数组去重——ES6(Set)
let arr=[1,2,3,4,5,3,5,6,2]; let a=new Set(arr); let b=[...a]; console.log(b);//[1,2,3,4,5,6]
注:性能优
13.2数组去重——创建空对象
1 let arr=[1,2,3,4,5,3,5,6,2]; 2 let b=[]; 3 let c={}; 4 for(let i=0;i<arr.length;i++){ 5 if(!c[arr[i]]){ 6 b.push(arr[i]); 7 c[arr[i]]='hello'; // 8 } 9 } 10 console.log(b);//[ 1, 2, 3, 4, 5, 6 ] 11 console.log(c); 12 /*{1: "hello", 2: "hello", 3: "hello", 4: "hello", 5: "hello", 6: "hello"}*/
注:性能最优
13.3数组去重——利用splice
function newArr(arr){ for(var i=0;i<arr.length;i++){ for(var j=i+1;j<arr.length;j++) if(arr[i]==arr[j]){ //如果第一个等于第二个,splice方法删除第二个 arr.splice(j,1); j--; } } return arr; } var arr = [1,1,2,5,6,3,5,5,6,8,9,8]; console.log(newArr(arr))
注:性能最差
13.4数组去重——利用filter
[1,2,3,1,'a',1,'a'].filter(function(ele,index,array){ return index===array.indexOf(ele) })
13.4数组去重——Array.sort()
function distinct(a, b) { let arr = a.concat(b) arr = arr.sort() let result = [arr[0]] for (let i=1, len=arr.length; i<len; i++) { arr[i] !== arr[i-1] && result.push(arr[i]) } return result; } console.log(distinct([4,3,2],[5,4,2])) //[2,3,4,5]
13.5字符串去重——ES6(set)
[...new Set('ababbc')].join('') // "abc"
14.1判断数组是否存在重复值
var arr=['333','222','222','444','333']; var s=arr.join(",")+","; for(var i=0;i<arr.length;i++){ if(s.replace(arr[i]+",","").indexOf(arr[i]+",")>0) alert("数组中有重复元素:" + arr[i]); }
14.2判断数组是否存在重复值(2)
var ary = new Array("111","22","33","111"); var nary=ary.sort(); for(var i=0;i<ary.length;i++){ if (nary[i]==nary[i+1]){ alert("数组重复内容:"+nary[i]); } }
14.3判断数组是否存在重复值(3)
function isRepeat(arr){ var hash = []; for(var i in arr) { if(hash[arr[i]]) return true; hash[arr[i]] = true; } return false; } var arr=["111","22","33","111"]; alert(isRepeat(arr))
15.获取浏览URL中查询字符串的参数
1 function showWindowHref(arr){ 2 var sHref = arr; 3 var args = sHref.split('?'); 4 if(args[0] == sHref){ 5 return ""; 6 } 7 var arr = args[1].split('&'); 8 alert(arr) //staffid=12333,name=xiaoming,age=23 9 var obj = {}; 10 for(var i = 0;i< arr.length;i++){ 11 var arg = arr[i].split('='); 12 obj[arg[0]] = arg[1]; 13 console.log(obj[arg[0]]) //12333,xiaomi,23 14 } 15 return obj; 16 } 17 var href = showWindowHref("https://www.runoob.com/jsref/met-win-close.html?staffid=12333&name=xiaoming&age=23"); // obj 18 alert(href['name']); // xiaoming
16.原生Ajax
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>原生的Ajax</title> 6 </head> 7 <body> 8 <h1></h1> 9 <script> 10 var xmlhttp; 11 load(); 12 function load(){ 13 if(window.XMLHttpRequest){ 14 xmlhttp=new XMLHttpRequest(); 15 // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 16 }else { 17 xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); 18 //IE6 5 19 } 20 xmlhttp.onreadystatechange=function(){ 21 if(xmlhttp.readyState===4&&xmlhttp.status===200){ 22 // 0: 请求未初始化 23 // 1: 服务器连接已建立 24 // 2: 请求已接收 25 // 3: 请求处理中 26 // 4: 请求已完成,且响应已就绪 27 // 200: "OK" 28 // 404: 未找到页面 29 //responseText代表字符串形式回应 responseXML代表XML形式回应 30 document.getElementsByTagName('h1')[0].innerHTML=xmlhttp.responseText; 31 } 32 }; 33 xmlhttp.open('GET','http://www.wangwei123.cn/xx/public/admin/aside/typelist',true);//TRUE代表异步 34 xmlhttp.send(); 35 } 36 </script> 37 </body> 38 </html>
1 100——客户必须继续发出请求 2 101——客户要求服务器根据请求转换HTTP协议版本 3 200——交易成功 4 201——提示知道新文件的URL 5 202——接受和处理、但处理未完成 6 203——返回信息不确定或不完整 7 204——请求收到,但返回信息为空 8 205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件 9 206——服务器已经完成了部分用户的GET请求 10 300——请求的资源可在多处得到 11 301——删除请求数据 12 302——在其他地址发现了请求数据 13 303——建议客户访问其他URL或访问方式 14 304——客户端已经执行了GET,但文件未变化 15 305——请求的资源必须从服务器指定的地址得到 16 306——前一版本HTTP中使用的代码,现行版本中不再使用 17 307——申明请求的资源临时性删除 18 400——错误请求,如语法错误 19 401——请求授权失败 20 402——保留有效ChargeTo头响应 21 403——请求不允许 22 404——没有发现文件、查询或URl 23 405——用户在Request-Line字段定义的方法不允许 24 406——根据用户发送的Accept拖,请求资源不可访问 25 407——类似401,用户必须首先在代理服务器上得到授权 26 408——客户端没有在用户指定的时间内完成请求 27 409——对当前资源状态,请求不能完成 28 410——服务器上不再有此资源且无进一步的参考地址 29 411——服务器拒绝用户定义的Content-Length属性请求 30 412——一个或多个请求头字段在当前请求中错误 31 413——请求的资源大于服务器允许的大小 32 414——请求的资源URL长于服务器允许的长度 33 415——请求资源不支持请求项目格式 34 416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段 35 417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求 36 500——服务器产生内部错误 37 501——服务器不支持请求的函数 38 502——服务器暂时不可用,有时是为了防止发生系统过载 39 503——服务器过载或暂停维修 40 504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长 41 505——服务器不支持或拒绝支请求头中指定的HTTP版本
17.短横线转换为驼峰命名
1 <script type="text/javascript"> 2 window.onload = function() { 3 new Camel('border-bottom-color'); 4 } 5 6 function Camel(str) { 7 this.result = ''; 8 this.arr = str.split('-'); 9 this.result += this.arr[0].toString(); 10 for(var i = 1; i < this.arr.length; i++) { 11 var str1 = this.arr[i].toString(); 12 var str2 = str1.charAt(0).toUpperCase(); 13 var str3 = str2 + str1.slice(1); 14 this.result += str3; 15 } 16 console.log(this.result); //borderBottomColor 17 } 18 </script>
18.vue实现简单购物车
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>vue综合练习</title> <style type="text/css"> td{ align-content: center; } </style> </head> <body> <div id="app"> <h3>购物车</h3> <h4 v-if="products.length==0">空空如也</h4> <div v-else> <table border="1" cellspacing="0" align="center"> <tr> <th>编号</th> <th>商品名称</th> <th>商品价格</th> <th>商品数量</th> <th>操作</th> </tr> <tr v-for="(product,index) in products"> <td>{{index+1}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td><button @click="reduce(index)">-</button>{{product.num}}<button @click="add(index)">+</button></td> <td><button @click="del(index)">删除</button></td> </tr <tr> <td colspan="5">总价:{{total}}</td> </tr> </table> </div> </div> <script type="text/javascript" src="vue.js" ></script> <script> var app = new Vue({ el: "#app", data: { products:[ {id:1,name:"西瓜",price:20.00,num:4}, {id:2,name:"牛奶",price:30.00,num:2}, {id:3,name:"榴莲",price:80.00,num:1} ], total:0 }, methods:{ //新版本写法:del(){} //删除商品 del (index) { this.products.splice(index,1); this.count(); }, //减少数量 reduce (index) { if(this.products[index].num>0){ this.products[index].num--; this.count(); } }, //增加商品数量 add (index){ this.products[index].num++; this.count(); }, //计算商品总价 count () { this.total=0; for(var i in this.products){ this.total+=this.products[i].price*this.products[i].num; } } }, //最后运行 mounted(){ this.count(); } }); </script> </body> </html>
18.2.vue实现简单购物车2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{margin:0;padding: 0;} .checkout-title { position: relative; margin-bottom: 41px; text-align: center; } .checkout-title span { position: relative; padding: 0 1em; background-color: #fff; font-family: "moderat", sans-serif; font-weight: bold; font-size: 20px; color: #605F5F; z-index: 1; } .checkout-title:before{ position: absolute; content: ''; border-bottom: 1px solid green; width: 100%; top:50%; left: 0; z-index: 0; } /* 居中线制作方法2 .checkout-title:before { position: absolute; /*相对定位取决于checkout-title的position:relative content: ""; height: 1px; //修改高度即可 width: 100%; top: 50%; left: 0; background: #ccc; z-index: 0; } */ </style> </head> <body> <div class="checkout-title"> <span>购物车</span> </div> </body> </html>
19.vue/react——卡片列表循环单击选中效果
<li v-for="(item,index) in filterAddress" v-bind:class="{'check': index == currentIndex}" @click="currentIndex=index"> /*filterAddress计算属性的方法值可以放在,充当数组*/ //@click="currentIndex=index"标明了将点击的索引值赋给currentIndex,index == currentIndex自身的索引和当前点击事件索引相同,则产生选中事件 /*当产生点击事件后,第一个currentIndex因为相等所以产生true,check类就可以渲染,v:bind和@click结合使用,会产生奇妙的状态!*/
<li v-for="(item,index) in filterAddress" v-bind:class="{'check': index == current && current !== ' '}" @click="current=index"> /*current默认为空,然后默认不会被选中*/
注:与1的手风琴效果类似
react的Tabbar实现
1 import React, { Component } from 'react' 2 import { Link } from 'react-router-dom' 3 import './index.css' 4 5 const tarbarArr = [ 6 { 7 img: 'icon-home', 8 text: '首页', 9 link: '/home' 10 }, 11 { 12 img: 'icon-icon04', 13 text: '分类', 14 link: '/category' 15 }, 16 { 17 img: 'icon-gouwuche', 18 text: '购物车', 19 link: '/car' 20 }, 21 { 22 img: 'icon-yonghu', 23 text: '我的', 24 link: '/user' 25 } 26 ] 27 28 export default class Tabbar extends Component { 29 constructor(props) { 30 super(props) 31 this.state = { 32 index: 0 33 } 34 } 35 36 itemChange = (i) => { 37 this.setState({ 38 index: i 39 }) 40 } 41 42 render() { 43 let Url = window.location.href 44 return ( 45 <div className='tabbar'> 46 <div className="tabbar-content"> 47 { 48 tarbarArr.map((v, i) => ( 49 // 点击选中效果(根据数字来判断) 50 // <Link to={v.link} key={i} className={"tabbar-item" + (this.state.index === i ? ' active' : '')} onClick={() => this.itemChange(i)}> 51 // 点击选中效果并跳转页面链接(根据链接来判断) 52 <Link to={v.link} key={i} className={"tabbar-item" + (Url.indexOf(v.link) > -1 ? ' active' : '')} onClick={() => this.itemChange(i)}> 53 <div className={'iconfont ' + v.img}></div> 54 <div>{v.text}</div> 55 </Link> 56 )) 57 } 58 </div> 59 </div> 60 ) 61 } 62 }
20.深度拷贝
var deepCopy = function(obj) { if (typeof obj !== 'object') return; var newObj = obj instanceof Array ? [] : {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key]; } } return newObj; }
<script type="text/javascript"> /* 思考: 如何实现深度拷贝(克隆) 拷贝的数据里有对象/数组 拷贝的数据里不能有对象/数组,即使有对象/数组可以继续遍历对象、数组拿到里边每一项值,一直拿到是基本数据类型,然后再去复制,就是深度拷贝。 */ //知识点储备 /* 如何判断数据类型:arr-Array null -Null 1.typeof返回的数据类型有:String,Number,Boolean,Undefined,Object,Function。 2.Object.prototype.toString.call(obj)。 */ let result = 'abcd'; result = null; result = [1,3]; console.log(Object.prototype.toString.call(result).slice(8,-1)); //[object Array],sclice截取字符串后:Array(拿到分类)。 //console.log(typeof Object.prototype.toString.call(result)); //string //for in 循环对象(属性名)、数组(下标),推荐在循环对象属性的时候,使用for...in,在遍历数组的时候的时候使用for...of。 //for in 循环遍历对象属性名 let obj = {username:'zhangsan',age:22}; for(let i in obj){ console.log(i); //username age } //for in 循环遍历数组下标 let arr = [1,3,'abc']; for(let i in arr){ //数组的可以用for of对应数组值 console.log(i); //0 1 2 } //定义检测数据类型的功能函数 function checkedType(target){ return Object.prototype.toString.call(target).slice(8,-1); } console.log(checkedType(result)); //Array //实现深度克隆--对象/数组 function clone(target){ //判断拷贝的数据类型 //初始化变量的result 成为最终克隆的数据 let result,targetType = checkedType(target); if(targetType === 'Object'){ result = {}; }else if(targetType === 'Array'){ result = []; }else{ return target; //如果是基本数据类型:(String, Number, boolean, Null, Undefined)就直接反回去。 } //遍历目标数据 for(let i in target){ //获取遍历数据结构的每一项值。 let value = target[i]; //i=1,i=2,i=.. //判断目标结构里的每一值是否存在对象/数组 if(checkedType(value) === 'Object' || checkedType(value) === 'Array'){ //如果对象OR数组里嵌套了对象/数组 //继续遍历获取到的value值 result[i] = clone(value); //这个只执行一次,数组里只有一个对象 }else{ //获取到的value值是基本的数据类型或者是函数。 result[i] = value; //因为arr3数组的下标0和1都是Number类型,只有下标2才是Object(转去执行1046行) } } return result; } let arr3 = [1,2,{username:'dudu',age:32}]; let arr4 = clone(arr3); //相当于复制了一份arr3的基本数据 console.log(arr4); arr4[2].username = 'gate'; arr4[2].age = 65; console.log(arr3,arr4); //arr3下标2是{username:'dudu':age:32},arr4下标2是{username:gate,age:65} </script>
21.ES6——Primise-async语法实现红绿灯
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>实现一个红绿灯</title> <style> #traffic-light { width: 50px; height: 50px; border-radius: 50%; border: 1px solid #000; } .traffic-box { display: flex; flex-direction: column; } .traffic { width: 50px; height: 50px; margin: 5px 0; border-radius: 50%; border: 1px solid #000; } .red { background-color: red;} .yellow { background-color: yellow;} .green { background-color: green;} </style> </head> <body> <header> <h1>实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色</h1> <p>Promise、async\await 语法实现</p> </header> <div id="traffic-light"></div> <hr/> <div class="traffic-box"> <div id="traffic-red" class="traffic"></div> <div id="traffic-yellow" class="traffic"></div> <div id="traffic-green" class="traffic"></div> </div> <script> function sleep(duration) { return new Promise(function(reslove){ setTimeout(reslove, duration); }) } async function changeColor(duration, color) { document.getElementById("traffic-light").style.background = color; await sleep(duration); } async function main(){ while(true){ await changeColor(3000,"green"); await changeColor(1000, "yellow"); await changeColor(2000, "red"); } } main() //*************************************************************** var red = document.getElementById('traffic-red') var yellow = document.getElementById('traffic-yellow') var green = document.getElementById('traffic-green') async function changeColor2(duration, color) { console.log(duration, color) if (color === 'red') { red.classList.add('red'); yellow.classList.remove('yellow') green.classList.remove('green') } else if (color === 'yellow') { yellow.classList.add('yellow'); red.classList.remove('red') green.classList.remove('green') } else { green.classList.add('green'); red.classList.remove('red') yellow.classList.remove('yellow') } await sleep(duration); } async function main2(){ while(true){ await changeColor2(3000,"green"); await changeColor2(1000, "yellow"); await changeColor2(2000, "red"); } } main2() </script> </body> </html>
22.HTML5拖拽图片上传及本地预览
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML5拖拽上传</title> <style> .upload-arae { min-width: 300px; min-height: 150px; border: 1px dashed #ccc; border-radius:3px; display: flex; justify-content: center; align-items: center; color: #ccc; margin-bottom: 10px; } .tip { text-align: center; } .dragover { border: 1px dashed blue; } .button { color: #fff; background-color: #20a0ff; border-color: #20a0ff; border-radius: 4px; font-size: 14px; padding: 5px 15px; cursor: pointer; } </style> </head> <body> <h1>HTML5拖拽上传及本地预览</h1> <div id="rate" class="upload-arae"> <div class="tip"> <p>将文件拖拽到此处开始上传!</p> <label for="inputFile" class="button">选择文件</label> <input type="file" name="file" id="inputFile" onchange="changeUpload(event)" style="display:none"> </div> </div> <div id="viewImg"> </div> </body> <script> //只能实现拖拽图片 var rate = document.getElementById('rate'); var viewImg = document.getElementById('viewImg'); document.addEventListener('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); rate.classList.add('dragover') }, false) document.addEventListener('dragover', function (e) { e.stopPropagation(); e.preventDefault(); }, false); document.addEventListener('drop', function (e) { e.stopPropagation(); e.preventDefault(); sendFile(e || window.event); rate.classList.remove('dragover') }, false); function sendFile(e) { var files = e.dataTransfer.files; console.log('files', files) if (!files || files.length < 1) { return; } toViewImg(files[0]) } function changeUpload(ev) { let files = ev.target.files; toViewImg(files[0]) } function toViewImg(file) { var reader = new FileReader(); reader.readAsDataURL(file) reader.onload = function (e) { viewImg.innerHTML = '上传中...' var img = this.result setTimeout(function(){ viewImg.innerHTML = '<img src="' + img + '" />' }, 2000) } } </script> </html>
23.使用js实现极简Vue.js双向数据绑定功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>实现极简Vue.js双向数据绑定</title> </head> <body> <div id="app"> <input type="text" v-model="message"> {{message}} </div> <script> function observer(obj, vm) { Object.keys(obj).forEach(function(key){ defineReactive(vm, key, obj[key]); }); } function defineReactive(obj, key, val) { var dep = new Dep(); Object.defineProperty(obj, key, { get: function() { console.log('Dep.target', Dep.target); if(Dep.target) dep.addSub(Dep.target); return val; }, set: function(newVal) { //检测更新的时候,会自动调用并传入新值 if(newVal === val) return; //没有更新,直接返回 val = newVal; dep.notify(); //发出通知 } }); } function Dep() { this.subs = []; } Dep.prototype = { addSub: function(sub) { this.subs.push(sub); }, notify: function() { this.subs.forEach(function(sub) { sub.update();//更新 }); } }; function nodeToFrangment(node, vm) { //node:ID元素 //渲染个数不确定 var flag = document.createDocumentFragment(); var child; while(child = node.firstChild) {//逐个渲染 compile(child, vm)//解析操作 flag.append(child); } return flag; } function compile(node, vm) { var reg = /\{\{(.*)\}\}/; //正则匹配{{}} var textType = 'input'; if(node.nodeType === 1) { //v-model var attrs = node.attributes; for (var i = 0; i < attrs.length; i++) { if(attrs[i].nodeName === 'v-model') { var name = attrs[i].nodeValue; node.addEventListener('input', function(e){ vm[name] = e.target.value;//对数据更新,调用set方法 }); node.value = vm[name]; node.removeAttribute('v-model'); } } } if(node.nodeType === 3) { //text if(reg.test(node.nodeValue)) { var name = RegExp.$1; name = name.trim(); textType = 'text'; } } new Watcher(vm, node, name, textType); } function Watcher(vm, node, name, nodeType) { Dep.target = this; this.name = name; this.vm = vm; this.node = node; this.nodeType = nodeType; this.update(); Dep.target = null; } Watcher.prototype = { update: function() { this.get(); if(this.nodeType === 'text') { this.node.nodeValue = this.value; } if(this.nodeType === 'input') { this.node.value = this.value; } }, get: function() {//获取data中的属性值 this.value = this.vm[this.name]; } }; function Vue(opt) { //更新数据 解析指令 this.data = opt.data; var data = this.data; observer(data, this); //监听数据 var id = opt.el; var dom = nodeToFrangment(document.getElementById(id), this); document.getElementById(id).appendChild(dom); } var v = new Vue({ el: 'app', data: { message: 'hello lucas' } }); </script> </body> </html>
<--! HTML代码--> <body> <p> input1=><input type="text" id="input1"> </p> <p> input2=> <input type="text" id="input2"> </p> <div> 我每次比input1的值加1=> <span id="span"></span> </div> </body> <--! JS代码--> var oInput1 = document.getElementById('input1'); var oInput2 = document.getElementById('input2'); var oSpan = document.getElementById('span'); var obj = {}; Object.defineProperties(obj, { val1: { configurable: true, get: function() { oInput1.value = 0; oInput2.value = 0; oSpan.innerHTML = 0; return 0 }, set: function(newValue) { oInput2.value = newValue; oSpan.innerHTML = Number(newValue) ? Number(newValue) : 0 } }, val2: { configurable: true, get: function() { oInput1.value = 0; oInput2.value = 0; oSpan.innerHTML = 0; return 0 }, set: function(newValue) { oInput1.value = newValue; oSpan.innerHTML = Number(newValue)+1; } } }) oInput1.value = obj.val1; oInput1.addEventListener('keyup', function() { obj.val1 = oInput1.value; }, false) oInput2.addEventListener('keyup', function() { obj.val2 = oInput2.value; }, false)
24.左中右三栏布局,中间自适应,5种布局方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>左中右三栏布局,中间自适应,5种布局方法</title> <style> body{ margin: 0; padding: 0; } /** FlexBox **/ .container{display: flex;} .container div{min-height: 100px;} .container .left, .container .right{width: 300px; background-color: orange;} .container .center{flex:1;background-color: #ccc;} /** Float **/ .container2 div{min-height: 100px;} .container2 .left, .container2 .right{background-color: palegreen;width: 300px;} .container2 .center{background-color: #ccc} .container2 .left{float: left;} .container2 .right{float: right;} /** absolute **/ .container3{min-height: 100px;} .container3 div{min-height: 100px;position: absolute;} .container3 .left, .container3 .right{background-color: palegreen;width: 300px;} .container3 .center{background-color: #ccc;left: 300px;right: 300px;} .container3 .left{left: 0;} .container3 .right{right: 0;} /** table **/ .container4{width: 100%;height: 100px;display: table;} .container4 div{display: table-cell;} .container4 .left, .container4 .right{background-color: palegreen;width: 300px;} .container4 .center{background-color: #ccc;} /** CSS Grid **/ .container5{ width: 100%; display: grid; grid-template-rows: 100px; grid-template-columns: 300px auto 300px; } .container5 div{min-height: 100px;} .container5 .left, .container5 .right{background-color: palegreen;} .container5 .center{background-color: #ccc;} /** 双飞翼(浮动) **/ .container6{ } .container6 div{min-height: 100px;} .container6 .left, .container6 .right{background-color: palegreen;} .container6 .center{background-color: #ccc;} </style> </head> <body> <!-- 假设高度已知,左右宽度各位三百,中间自适应 --> <h1>左中右三栏布局,中间自适应</h1> <h2>1. FlexBox方案</h2> <div class="container"> <div class="left"></div> <div class="center"> 左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局, 中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案左中右三栏布局,中间自适应,FlexBox方案 </div> <div class="right"></div> </div> <h2>2. Float方案</h2> <div class="container2"> <div class="left"></div> <div class="right"></div> <div class="center"> 左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应, Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应,Float方案左中右三栏布局,中间自适应 </div> </div> <h2>3. 绝对定位方案</h2> <div class="container3"> <div class="left"></div> <div class="center"> 左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局, 中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案左中右三栏布局,中间自适应,绝对定位方案 </div> <div class="right"></div> </div> <h2>4. 格布局方案</h2> <div class="container4"> <div class="left"></div> <div class="center"> 左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应 左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应,表格布局方左中右三栏布局,中间自适应, </div> <div class="right"></div> </div> <h2>5. 网格布局方案</h2> <div class="container5"> <div class="left"></div> <div class="center"> 左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案 左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案左中右三栏布局,中间自适应,网格布局方案 </div> <div class="right"></div> </div> <h2>6. 双飞翼(浮动)布局方案</h2> <div class="container6"> <div class="main"> <div class="center"> 双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案 双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案双飞翼(浮动)布局方案 </div> </div> <div class="left"></div> <div class="right"></div> </div> </body> </html>
25.DIV模板引擎
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DIV模板引擎</title> </head> <body> <h1>DIV模板引擎</h1> <script> var Template = function (tempstr, data) { var re = /<%([^%>]+)?%>/g, cursor = 0, // 字符串的查找位置 reExp = /^\s*(for|if|else|switch|case|break|continue|{|})(.*)?/g, code = 'var arr = [];\n'; var add = function (line, flag) { //flag --> 判断是否是JS代码 // 第一次:line ==> 我的名字是: code += flag ? line.match(reExp) ? line : 'arr.push(' + line + ');\n' : 'arr.push("' + line.replace(/"/, '\\"') + '");\n'; } while (item = re.exec(tempstr)) { add(tempstr.slice(cursor, item.index)); add(item[1], true); cursor = item.index + item[0].length; } add(tempstr.substring(cursor)); code += 'return arr.join("");'; return new Function(code.replace(/[\r\n\t]/g, '')).apply(data); } // var str = '我的名字是:<%this.name%>,年龄是:<%this.profile.age%>,Over!!!'; // var res = Template(str, { // name: 'Dunizb', // profile: { // age: 22 // } // }); // console.log(res); var str = '我的爱好:<%for(var i in this.hobby){%>' + '<p><%this.hobby[i]%></p>' + '<%}%>'; var res = Template(str, { hobby: ['php', 'java', 'javascript', 'linux', 'python'] }); document.write(res); </script> </body> </html>
26.省市两级级联下拉列表
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>省市两级级联下拉列表</title> </head> <body> <select id="province"> <option>==请选择省份==</option> </select> <select id="city"> <option>==请选择城市==</option> </select> </body> <script> // 准备数据 var data = [ {"code" : "0001", "name" : "广东省", "cities" : [ {"code" : "00010001", "name" : "广州市"}, {"code" : "00010002", "name" : "深圳市"}, {"code" : "00010003", "name" : "东莞市"} ] }, {"code" : "0002", "name" : "湖南省", "cities" : [ {"code" : "00020001", "name" : "长沙市"}, {"code" : "00020002", "name" : "衡阳市"}, {"code" : "00020003", "name" : "郴州市"} ] }, {"code" : "0003", "name" : "江西省", "cities" : [ {"code" : "00030001", "name" : "南昌市"}, {"code" : "00030002", "name" : "赣州市"}, {"code" : "00030003", "name" : "吉安市"} ] } ]; window.onload = function(){ // 获取省份城市select var proSelect = document.getElementById("province"); for (var i = 0; i < data.length; i++){ var json = data[i]; var option = new Option(json.name, json.code, false, false); proSelect.add(option); } // 为proSelect绑定onChange事件 proSelect.onchange = function(){ var citySelect = document.getElementById("city"); // 在下次选择省份之前先清空城市下拉列表 for (var i = citySelect.length - 1; i > 0; i--){ citySelect.remove(i); } for (var i = 0; i < data.length; i++){ var json = data[i]; if (json.code == this.value){ // 取城市 var cities = json.cities; for (var j = 0; j < cities.length; j++){ // 获取其中的json var temp = cities[j]; var option = new Option(temp.name, temp.code, false, false); citySelect.add(option); } } } } } </script> </html>
27.CSS3——打字延迟动画
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>打字动画</title> <style> body {background-color: #000;color:green;} p { width: 27em; /*这里控制打字的宽度和子长,也可以取消下面的JS注释 */ font-family: Menlo, Monaco, Consolas, "Courier New", monospace; overflow: hidden; white-space: nowrap; border-right: .05em solid transparent;/*兼容处理*/ border-right: .05em solid; animation: typing 6s steps(16), caret 1s steps(1) infinite; } @keyframes typing { from { width: 0; } } @keyframes caret { 50% { border-right-color: transparent; } } </style> </head> <body> <p>Javascript是世界最好的语言,hello world,hello lucas!</p> <script> /*** 此段JS代码的目的是为了动态设置文字的宽度和步长 ****/ // var ps = document.getElementsByTagName("p"); // for(var i=0 ;i<ps.length; i++){ // var len = ps[i].textContent.length; // ps[i].style.width = len + 'em'; // ps[i].style.animationTimingFunction = "steps("+len+"),steps(1)"; // } </script> </body> </html>
28.CSS3——文字闪烁动画
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>文字闪烁</title> <style> .hightlight { width: 500px; margin: 100px auto; font:700 20px/20px "Microsoft YaHei"; animation: 1s blink 3 steps(1) ; } @keyframes blink { 50% { color: transparent; } } </style> </head> <body> <div class="hightlight">hello lucas</div> </body> </html>
29.数组与字符串对象相同的方法
concat()
indexOf()
lastIndexOf()
includes()
toString()
slice()
30.找出数组最大个数
//es5写法 function maxNumber(){ var arr = [10,29,5] document.write(Math.max.apply(null,arr)) }
//es6拓展运算符... Math.max(...arr)
arr.sort((num1, num2) => { return num1 - num2 < 0 }) arr[0]
let max = arr[0]; for (let i = 0; i < arr.length - 1; i++) { max = max < arr[i+1] ? arr[i+1] : max }
31.JS简单数组排序
function sortNumber(a,b) { return a - b; //如果需要降序排序可以把a与b调换即可 } var arr = new Array(6) arr[0] = "10" arr[1] = "5" arr[2] = "40" arr[3] = "25" arr[4] = "1000" arr[5] = "1" document.write(arr + "<br />") document.write(arr.sort(sortNumber))
var arr = [1, 7, 10, 4, 6]; function compare(val1, val2) { if(val1 < val2) { return -1; } else if(val1 > val2) { return 1; } else { return 0; } }; arr.sort(compare); console.log(arr);
32.对数组进行随机排序
var points = [40, 100, 1, 5, 25, 10]; function myFunction() { return points.sort(function(a, b){return 0.5 - Math.random()}); }
33.为不具备 Iterator 接口的对象提供遍历方法
function* objectEntries(obj) { const propKeys = Reflect.ownKeys(obj); for (const propKey of propKeys) { yield [propKey, obj[propKey]]; } } const jane = { first: 'Jane', last: 'Doe' }; for (const [key,value] of objectEntries(jane)) { console.log(`${key}: ${value}`); } // first: Jane // last: Doe //Reflect.ownKeys() 返回对象所有的属性,不管属性是否可枚举,包括 Symbol。
34.嵌套数组的平铺
function* iterTree(tree) { if (Array.isArray(tree)) { for(let i=0; i < tree.length; i++) { yield* iterTree(tree[i]); } } else { yield tree; } } const tree = [ 'a', ['b', 'c'], ['d', 'e'] ]; for(let x of iterTree(tree)) { console.log(x); } // a // b // c // d // e //由于扩展运算符...默认调用 Iterator 接口,所以上面这个函数也可以用于嵌套数组的平铺。 `[...iterTree(tree)] // ["a", "b", "c", "d", "e"]`
35.Markdown源码
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>md转换为html</title> 7 <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script> 8 </head> 9 10 <body> 11 <div style="font-size: 20px;height: 30px; text-align: center;color: #009689; font-weight: bold;">Markdown转换为HTML的Demo</div> 12 <style> 13 .markdown-here-wrapper { 14 font-size: 16px; 15 line-height: 1.8em; 16 letter-spacing: 0.1em; 17 } 18 19 pre, 20 code { 21 font-size: 14px; 22 font-family: Roboto, 'Courier New', Consolas, Inconsolata, Courier, monospace; 23 margin: auto 5px; 24 } 25 26 code { 27 white-space: pre-wrap; 28 border-radius: 2px; 29 display: inline; 30 } 31 32 pre { 33 font-size: 15px; 34 line-height: 1.4em; 35 display: block; 36 !important; 37 } 38 39 pre code { 40 white-space: pre; 41 overflow: auto; 42 border-radius: 3px; 43 padding: 1px 1px; 44 display: block !important; 45 } 46 47 strong, 48 b { 49 color: #BF360C; 50 } 51 52 em, 53 i { 54 color: #009688; 55 } 56 57 hr { 58 border: 1px solid #BF360C; 59 margin: 1.5em auto; 60 } 61 62 p { 63 margin: 1.5em 5px !important; 64 } 65 66 table, 67 pre, 68 dl, 69 blockquote, 70 q, 71 ul, 72 ol { 73 margin: 10px 5px; 74 } 75 76 ul, 77 ol { 78 padding-left: 15px; 79 } 80 81 li { 82 margin: 10px; 83 } 84 85 li p { 86 margin: 10px 0 !important; 87 } 88 89 ul ul, 90 ul ol, 91 ol ul, 92 ol ol { 93 margin: 0; 94 padding-left: 10px; 95 } 96 97 ul { 98 list-style-type: circle; 99 } 100 101 dl { 102 padding: 0; 103 } 104 105 dl dt { 106 font-size: 1em; 107 font-weight: bold; 108 font-style: italic; 109 } 110 111 dl dd { 112 margin: 0 0 10px; 113 padding: 0 10px; 114 } 115 116 blockquote, 117 q { 118 border-left: 2px solid #009688; 119 padding: 0 10px; 120 color: #777; 121 quotes: none; 122 margin-left: 1em; 123 } 124 125 blockquote::before, 126 blockquote::after, 127 q::before, 128 q::after { 129 content: none; 130 } 131 132 h1, 133 h2, 134 h3, 135 h4, 136 h5, 137 h6 { 138 margin: 20px 0 10px; 139 padding: 0; 140 font-style: bold !important; 141 color: #009688 !important; 142 text-align: center !important; 143 margin: 1.5em 5px !important; 144 padding: 0.5em 1em !important; 145 } 146 147 h1 { 148 font-size: 24px !important; 149 border-bottom: 1px solid #ddd !important; 150 } 151 152 h2 { 153 font-size: 20px !important; 154 border-bottom: 1px solid #eee !important; 155 } 156 157 h3 { 158 font-size: 18px; 159 } 160 161 h4 { 162 font-size: 16px; 163 } 164 165 166 table { 167 padding: 0; 168 border-collapse: collapse; 169 border-spacing: 0; 170 font-size: 1em; 171 font: inherit; 172 border: 0; 173 margin: 0 auto; 174 } 175 176 tbody { 177 margin: 0; 178 padding: 0; 179 border: 0; 180 } 181 182 table tr { 183 border: 0; 184 border-top: 1px solid #CCC; 185 background-color: white; 186 margin: 0; 187 padding: 0; 188 } 189 190 table tr:nth-child(2n) { 191 background-color: #F8F8F8; 192 } 193 194 table tr th, 195 table tr td { 196 font-size: 16px; 197 border: 1px solid #CCC; 198 margin: 0; 199 padding: 5px 10px; 200 } 201 202 table tr th { 203 font-weight: bold; 204 color: #eee; 205 border: 1px solid #009688; 206 background-color: #009688; 207 } 208 </style> 209 <style> 210 #area>table { 211 width: 100%; 212 table-layout: fixed; 213 } 214 215 #area table tr td { 216 margin: 0; 217 padding: 6px; 218 border: 0; 219 220 } 221 222 223 #md-area { 224 225 width: 100%; 226 height: 600px; 227 font-size: 18px; 228 overflow: hidden; 229 font-weight: bold; 230 outline: none; 231 } 232 233 #show-area { 234 height: 600px; 235 background-color: #FCF6E5; 236 } 237 238 .clearfix:before { 239 content: ""; 240 display: table; 241 } 242 </style> 243 <script> 244 function mdSwitch() { 245 var mdValue = document.getElementById("md-area").value; 246 var converter = new showdown.Converter(); 247 var html = converter.makeHtml(mdValue); 248 document.getElementById("show-area").innerHTML = html; 249 } 250 </script> 251 <div id="area"> 252 <table> 253 <tr> 254 <td><textarea name="" id="md-area" onkeyup=mdSwitch()></textarea></td> 255 <td> 256 <div id="show-area" class="clearfix"></div> 257 </td> 258 </tr> 259 </table> 260 </div> 261 </body> 262 263 </html>
36.筛选数组数据
<script type="text/javascript"> //创建数组 var arr = ['*','##',"***","&&","****","##*"]; arr[7] = "**"; //数组长度 var l = arr.length; //删除数组中非*的项 for(var i = 0; i < l; i++){ var val = arr[i]; if(val != undefined) { var newarr = val.split(''); var newl = newarr.length; for(var j = 0; j < newl; j++){ if(newarr[j] != '*'){ arr.splice(i, 1); break; } } } } //按照字符数排序 arr.sort(function(a, b){ if(a.length > b.length){ return 1 }else if(a.length < b.length){ return -1 }else{ return 0 } }) //将数组内容输出,完成达到的效果。 for(var i = 0; i < l; i++){ if(arr[i] != undefined){ document.write(arr[i] + '<br />') } } </script>
<script type="text/javascript"> //第一步把之前的数据写成一个数组的形式,定义变量为 infos var infos=[ ['小A','女',21,'大一'], ['小B','男',23,'大三'], ['小C','男',24,'大四'], ['小C','男',24,'大四'], ['小D','女',21,'大一'], ['小E','女',22,'大四'], ['小F','男',21,'大一'], ['小G','女',22,'大二'], ['小H','女',20,'大三'], ['小I','女',20,'大一'], ['小J','男',20,'大三'] ]; //第一次筛选,找出都是大一的信息 var i=0; var length=infos.length; for(i=0;i<length;i++){ if(infos[i][3]=='大一'&&infos[i][1]=='女'){ document.write(infos[i][0] + "  "+ infos[i][3]+"</br>"); } } //第二次筛选,找出都是女生的信息 </script>
37.简单加减乘除计算器
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>加减乘除计算器</title> 5 <script type="text/javascript"> 6 function count(){ 7 8 //获取第一个输入框的值 9 var a=document.getElementById("txt1").value; 10 //获取第二个输入框的值 11 var b=document.getElementById("txt2").value; 12 //获取选择框的值 13 var c=document.getElementById("select").value; 14 var sum=""; 15 switch(c) 16 { 17 case '+': 18 sum=parseFloat(a) + parseFloat(b); 19 break; 20 case '-': 21 sum=parseFloat(a) - parseFloat(b); 22 break; 23 case '*': 24 sum=parseFloat(a) * parseFloat(b); 25 break; 26 default: 27 sum=parseFloat(a) / parseFloat(b); 28 break; 29 30 } 31 document.getElementById("fruit").value=sum; 32 } 33 </script> 34 </head> 35 <body> 36 <input type='text' id='txt1' /> 37 <select id='select'> 38 <option value='+'>+</option> 39 <option value="-">-</option> 40 <option value="*">*</option> 41 <option value="/">/</option> 42 </select> 43 <input type='text' id='txt2' /> 44 <input type='button' value=' = ' onclick="count()" /> <!--通过 = 按钮来调用创建的函数,得到结果--> 45 <input type='text' id='fruit' /> 46 </body> 47 </html>
38.js实现随机选取10——100之间的10个数字
var iArray=[]; function getRandom(istart,iend){ var iChoice=istart-iend+1; return Math.floor(Math.random()*iChoice+istart); } for(var i=0;i<10;i++){ iArray.push(getRandom(10,100)); } iArray.sort()
39.删除数组中的null、undefined以及empty值
var a=[123, undefined, undefined, undefined, 8567, 213]; var b = [];//去除undefined后的结果 for(var i=0;i<a.length;i++){ if(typeof(a[i])!='undefined'){ //或者a[i]!='undefined' b.push(a[i]); } }
/*1只删除存在undefined和empty(空数组)的数组*/ let arr1 = [123, undefined, undefined, undefined, 8567, empty, 213]; //empty不能直接设置,是通过delete arr1[5]来产生的 arr2 = arr1.filter(function(item,index,arr){ return typeof arr[index] != 'undefined' }) //[123, 8567, 213] /*2.只删除存在有null的数组*/ let arr1 = [533, 213, null, 237, empty, 789]; arr2 = arr1.filter(function(item,index,arr){ return arr[index] != null }) // [533, 213, 237, 789] /*3.同时删除存在undefined、empty以及null的数组*/ let arr1 = [123, undefined, empty, 8567, null, null, 213]; let arr2 = []; for(let i =0;i<arr1.length;i++){ if(arr1[i]!=undefined || arr1[i]!=null) //注意undefined不能加引号 arr2.push(arr1[i]) } //[123, 8567, 213]
40.计算各个字符串出现的次数
1 //1.计算成数组 2 function strNubAry(str){ 3 var ary = []; 4 fnFas(str); 5 6 function fnFas(str){ 7 var s1 = str.charAt(0); //首次得到数字2,第二次递归得到数字3 8 var _str = ''; 9 var n = 0; //存放每个字符被计算出现的数量 10 11 //每for循环结束都只获得一个数组元素(被计算字符=次数) 12 for (var i = 0; i < str.length; i++) { 13 if(str.charAt(i) == s1){ 14 n++; 15 }else{ 16 _str += str.charAt(i); //语句首次被执行获得字符是3 17 // console.log("i="+i+" s1=="+s1+" _str="+_str); //试数 18 } 19 } 20 21 ary.push(s1+'='+n) 22 23 //首次执行到此处_str.length长度等于28(_str值除了数字2以外) 24 if(_str.length > 0){ 25 fnFas(_str); //递归 26 } 27 } 28 29 return ary; 30 } 31 32 var str = '2231452erfsdg35@#¥%63erefds我是大神'; 33 34 console.log(strNubAry(str)); 35 36 /* 输出结果各个字符出现的次数: 37 [ 38 "2=3", "3=3", "1=1", "4=1", "5=2", "e=3", "r=2", "f=2", "s=2", "d=2", "g=1", 39 "@=1", "#=1", "¥=1", "%=1", "6=1", "我=1", "是=1", "大=1", "神=1" 40 ] 41 */ 42 43 //2.计算成对象 44 function strNubObj(str){ 45 var obj = {}; 46 var ary = []; 47 fnFas(str); 48 function fnFas(str){ 49 var s1 = str.charAt(0); 50 var _str = ''; 51 var n = 0; 52 53 for (var i = 0; i < str.length; i++) { 54 if(str.charAt(i) == s1){ 55 n++; 56 }else{ 57 _str += str.charAt(i); 58 } 59 } 60 try{ 61 eval('obj.'+s1+'='+n) 62 }catch(err){ 63 ary.push(s1+'='+n) 64 } 65 66 if(_str.length > 0){ 67 fnFas(_str); 68 } 69 } 70 71 if(ary.length > 0){ 72 obj.aNumber = ary; 73 } 74 return obj; 75 }
1 var arr = "1111245742157"; 2 var count = 0; 3 var czarr = ""; 4 for (var i = 0; i < arr.length; i++) { 5 for (var o = 0; o < arr.length; o++) { 6 if (parseInt(arr.charAt(i)) == parseInt(arr[o])) { 7 count++; 8 } 9 } 10 console.log(+arr.charAt(i)+"==="+count) 11 12 if (count > 1) { 13 czarr += arr.charAt(i); 14 } 15 count = 0; 16 }
41. Vue根据文件名引入组件
// 1.场景:如页面需要导入多个组件,原始写法: import titleCom from '@/components/home/titleCom' import bannerCom from '@/components/home/bannerCom' import cellCom from '@/components/home/cellCom' components:{titleCom,bannerCom,cellCom} // 2.这样就写了大量重复的代码,利用 require.context 可以写成: const path = require('path') const files = require.context('@/components/home', false, /\.vue$/) const modules = {} files.keys().forEach(key => { const name = path.basename(key, '.vue') modules[name] = files(key).default || files(key) }) components:modules // 这样不管页面引入多少组件,都可以使用这个方法
42. 微信公众号开发的XML数据转换未JS数据
1 // 未转换前 2 { xml: 3 { ToUserName: [ 'gh_4ed7f86e2632' ], 4 FromUserName: [ 'o4e1muI8ddc_hOQywwZMfULNZggs' ], 5 CreateTime: [ '1594503273' ], 6 MsgType: [ 'text' ], 7 Content: [ '宇宙' ], 8 MsgId: [ '22827797029848854' ] } 9 } 10 11 // 转换后 12 { 13 ToUserName: 'gh_4ed7f86e2632', 14 FromUserName: 'o4e1muI8ddc_hOQywwZMfULNZggs', 15 CreateTime: '1594503307', 16 MsgType: 'text', 17 Content: '测试一下', 18 MsgId: '22827801219160825' 19 } 20 21 // 方法 22 function formatObjectData({ xml }) { 23 // let xml = data.xml 24 let result = {} 25 for (let key in xml) { 26 console.log('这里会被执行多少次呢') 27 result[key] = xml[key][0] 28 } 29 return result 30 }
43. JS实现动态延迟打字效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="text"> 9 10 </div> 11 </body> 12 <script> 13 let divTyping = document.getElementById('text') 14 let i = 0, 15 timer = 0, 16 str = '用JS实现动态打字效果' 17 18 function typing () { 19 if (i <= str.length) { 20 divTyping.innerHTML = str.slice(0, i++) + '_' 21 timer = setTimeout(typing, 200) 22 } 23 else { 24 divTyping.innerHTML = str//结束打字,移除 _ 光标 25 clearTimeout(timer) 26 } 27 } 28 29 typing() 30 </script> 31 </html>
44. for循环延迟执行函数
1 // 方法1 2 // 将延迟函数封装成 promise 对象 3 function lcWait(milliseconds) { 4 return new Promise((resolve, reject) => { 5 setTimeout(() => { 6 resolve('成功执行延迟函数, 延迟: ' + milliseconds) 7 }, milliseconds) 8 }) 9 } 10 11 async function spider() { 12 let allPageNum = await getNum() 13 for (let i = 1; i <= allPageNum; i++) { 14 // 延迟函数避免封IP 15 let waitTime = await lcWait(5000 * i) 16 console.log(waitTime); 17 } 18 } 19 20 // 方法2 21 function fn(a) { 22 return function () { 23 console.log(a); 24 } 25 } 26 27 function start() { 28 for (let i = 1; i < 5; i++) { 29 setTimeout(fn(i), i * 1000) 30 } 31 } 32 33 start() 34 35 36 // 方法3 37 function sleep(numberMillis) { 38 var now = new Date(); 39 var exitTime = now.getTime() + numberMillis; 40 while (true) { 41 now = new Date(); 42 if (now.getTime() > exitTime) 43 return; 44 } 45 } 46 47 48 for (let i = 1; i < 5; i++) { 49 console.info(i); 50 sleep(3000); 51 }
45. 将时间戳转换为普通日期格式
下面的是将秒转换不是毫秒:
new Date(parseInt(1476364740) * 1000).toLocaleString().substr(0,17).split('/').join('-')
毫秒转换为普通时间方法:new Date(1597687066633)
获取指定时间的毫秒时间戳方法:var time = new Date('2019-11-11').getTime(); 或者 new Date().valueOf() 获取当前时间的毫秒时间戳方法:var time = new Date('2019-11-11').getTime(); var time=(new Date()).toLocaleDateString()//获取当前日期 time =time.replace(/\//g,'-'); // "2020-8-18" // 接收的是秒而不是毫秒 function getLocalTime(nS) { return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17) } getLocalTime(1476364740) // "2016/10/13 下午9:19"
46. 一键复制网页内容
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>一键复制网页内容</title> 6 </head> 7 <body> 8 <textarea cols="20" rows="10" id="text">我是被复制的内容:Im lucas</textarea> 9 <input type="button" onClick="copyText()" value="点击复制方框内容" /> 10 </body> 11 <script> 12 function copyText() { 13 var Url2 = document.getElementById('text') 14 Url2.select() // 选择对象 15 document.execCommand('copy') // 执行浏览器复制命令用户定义的代码区域用户定义的代码区域 16 alert('已复制好,可贴粘。') //复制里面的内容 17 } 18 </script> 19 </html>
待续......
静则思,思则变,变则通,通则达