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>
View Code
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 }
View Code
3.多级导航菜单
1 <script>
2 window.οnlοad=function(){
3 var aLi=document.getElementsByTagName('li');
4
5 for(var i=0; i<aLi.length; i++){
6 aLi[i].οnmοuseοver=function(){
7 //鼠标经过一级菜单,二级菜单动画下拉显示出来
8 var subNav=this.getElementsByTagName("ul")[0];
9 subNav.className='';
10 //alert(subNav.innerHTML);
11 }
12 //鼠标离开菜单,二级菜单动画收缩起来。
13 aLi[i].οnmοuseοut=function(){
14 var subNav=this.getElementsByTagName("ul")[0];
15 subNav.className="subNav";
16 }
17 }
18 }
19 </script>
View Code
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 }
View Code
5.小时钟显示
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5
6 <title>Date</title>
7 </head>
8 <body οnlοad="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>
View Code
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" οnchange="upperCase(this.id)">
16
17 </body>
18 </html>
View Code
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" οnkeydοwn="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>
View Code
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>
View Code
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>
View Code
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>
View Code
11.检测数据类型
function checkedType(target){
return Object.prototype.toString.call(target).slice(8,-1);
}
View Code
<script>
let str=1234;
let str3=str.constructor.toString(); //返回:function Number() { [native code] }
alert(str3.slice(9,-20))
</script>
View Code
12.数组去重——Array.filter()
let arr=[2,3,4,2,3];
console.log(arr.filter(function(item,index,self){
return self.indexOf(item)==index}
)
)
View Code
注:性能差
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);
View Code
注:性能良好
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]
View Code
注:性能优
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"}*/
View Code
注:性能最优
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))
View Code
注:性能最差
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]
View Code
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]);
}
View Code
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]);
}
}
View Code
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))
View Code
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
View Code
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>
View Code
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版本
View Code
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>
View Code
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>
View Code
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>
View Code
19.vue——卡片列表循环单击选中效果
<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结合使用,会产生奇妙的状态!*/
View Code
<li v-for="(item,index) in filterAddress" v-bind:class="{'check': index == current && current !== ' '}" @click="current=index">
/*current默认为空,然后默认不会被选中*/
View Code
注:与1的手风琴效果类似
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;
}
View Code
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>
View Code
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" οnchange="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>
View Code
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>
View Code
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>
View Code
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>
View Code
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>
View Code
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>
View Code
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>
View Code
待续......