# Knowledge Code Guide

学习编程知识与笔记

## 2018年学习Html+CSS

## 2019年学习Javascript+PHP

## 2020年学习微信小程序


# Dictionary

| **Name**                | **Example**                                  |
| ----------------------- | -------------------------------------------- |
| \<a>\</a>               | \<a src="domian.com">happy\</a>              |
| \<button>\</button>     | \<button onclick="change()">Click!\</button> |
| \<body>\</body>         |                                              |
| \<div>\</div>           | \<div id="demo">\</div>                      |
| \<head>\</head>         |                                              |
| \<html>\</html>         |                                              |
| \<img>                  | \<img src="img.jpg" alt="mypic">             |
| \<link>                 | \<link href="css.css">                       |
| \<p>\</p>               | \<p class="demo">\</p>                       |
| \<script>               | \<script src="javascript.js">                |
| \<span>\</span>         | \<span>Hello\</span>                         |
| \<textarea>\</textarea> |                                              |
| \<title>\</title>       | \<title>My First\</title>                    |
| <><>                    |                                              |


# Dictionary

| **Name**    | **example**                                                      |
| ----------- | ---------------------------------------------------------------- |
| a:hover     | <p>a:hover{</p><p>  opacity:100%;</p><p>}</p>                    |
| align-items | align-items:center;                                              |
| border      | border: dotted solid double dashed;                              |
| bottom      | bottom:-10px;                                                    |
| color       | #ff8800;                                                         |
| height      | height:100px;                                                    |
| left        | left:10px;                                                       |
| margin      | <p>/*top-right-bottom-left*/</p><p>margin:0 auto;</p>            |
| opacity     | opacity:60%;                                                     |
| padding     | <p>/*top-right-bottom-left*/</p><p>padding:10px 5px 5px 10px</p> |
| position    | <p>absolute</p><p>inherit</p><p>relative</p>                     |
| right       | right:-10px;                                                     |
| top         | top:10px;                                                        |
| width       | width:100px;                                                     |


# Dictionary

A-Z

| ***Name***                   | ***Examples***                                                                                                                                                                                                                                                                                     |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \[...array]                  | <p>var a = \[1,2,3,4,5]</p><p>\[...a] //Equal to \[1,2,3,4,5]</p>                                                                                                                                                                                                                                  |
| \`Hello ${a}\`               | var a = "John" //Equal to "Hello John"                                                                                                                                                                                                                                                             |
| abs()                        | Math.abs(-1.234)                                                                                                                                                                                                                                                                                   |
| add()                        | var unique = new Set(\[1,2,3,4,5])                                                                                                                                                                                                                                                                 |
| alert()                      | alert("happy new year")                                                                                                                                                                                                                                                                            |
| acos()                       | Math.acos(0.4) //Equal to 1.1592794807274085                                                                                                                                                                                                                                                       |
| acosh()                      | Math.acosh(4) //Equal to 2.0634370688955608                                                                                                                                                                                                                                                        |
| addEventListener()           |                                                                                                                                                                                                                                                                                                    |
| altkey                       | function isKeyPressed(event) { if (event.altKey) { document.getElementsByTagName("p")\[0].style.color = "#ff0000"; } else { alert("The ALT key was NOT pressed!"); } }                                                                                                                             |
| appendChild                  |                                                                                                                                                                                                                                                                                                    |
| appCodeName                  | navigator.appCodeName                                                                                                                                                                                                                                                                              |
| appName                      | navigator.appName                                                                                                                                                                                                                                                                                  |
| appVersion                   | navigator.appVersion                                                                                                                                                                                                                                                                               |
| asin()                       | Math.asin(-0.4) //Equal to -0.41151684606748806                                                                                                                                                                                                                                                    |
| asinh()                      | Math.asinh(20) //Equal to 3.6895038689889055                                                                                                                                                                                                                                                       |
| assign()                     | <p>const target = { a: 1, b: 2 }; <br>const source = { b: 4, c: 5 };</p><p>const returnedTarget = Object.assign(target, source);</p><p>console.log(target); // expected output: Object { a: 1, b: 4, c: 5 }</p><p>console.log(returnedTarget); // expected output: Object { a: 1, b: 4, c: 5 }</p> |
| atan()                       | Math.atan(20) //Equal to 1.5208379310729538                                                                                                                                                                                                                                                        |
| atanh()                      | Math.atanh(0.2) //Equal to 0.2027325540540822                                                                                                                                                                                                                                                      |
| attribute                    |                                                                                                                                                                                                                                                                                                    |
| availHeight                  | screen.availHeight                                                                                                                                                                                                                                                                                 |
| boolean? a : b               | 4===5? true : false //Equal to false                                                                                                                                                                                                                                                               |
| break                        |                                                                                                                                                                                                                                                                                                    |
| cbrt()                       | Math.cbrt(8) //Equal to 2                                                                                                                                                                                                                                                                          |
| ceil()                       | Math.ceil(2.145) //Equal to 3                                                                                                                                                                                                                                                                      |
| charAt(num)                  | "nop".charAt(1) //Equal to "o"                                                                                                                                                                                                                                                                     |
| childNodes                   | <p>var c = document.body.childNodes;</p><p>c\[0];</p>                                                                                                                                                                                                                                              |
| clearInterval()              | clearInterval(setInterval(alert("Hi")),3000)                                                                                                                                                                                                                                                       |
| click                        |                                                                                                                                                                                                                                                                                                    |
| colorDepth                   | screen.colorDepth                                                                                                                                                                                                                                                                                  |
| confirm()                    | confirm("happy new year")                                                                                                                                                                                                                                                                          |
| concat()                     | \[1,2,3,4].concat(\[5],\[6]) //Equal to \[1,2,3,4,5,6]                                                                                                                                                                                                                                             |
| console.log()                | console.log("1+2")                                                                                                                                                                                                                                                                                 |
| const                        | const a = "apple" //globle                                                                                                                                                                                                                                                                         |
| continue                     |                                                                                                                                                                                                                                                                                                    |
| copyWithin()                 | \[1,2,3,4,5].copyWithin(2,1) //Equal to \[1,2,2,3,4]                                                                                                                                                                                                                                               |
| cos()                        | Math.cos(32) //Equal to 0.8342233605065102                                                                                                                                                                                                                                                         |
| cosh()                       | Math.cosh(32) //Equal to 39481480091340.34                                                                                                                                                                                                                                                         |
| cost()                       | Math.cost()                                                                                                                                                                                                                                                                                        |
| createElement()              | var para = document.createElement("p")                                                                                                                                                                                                                                                             |
| createTextNode()             | document.createTextNode("This is new.")                                                                                                                                                                                                                                                            |
| close()                      | window\.close()                                                                                                                                                                                                                                                                                    |
| Date()                       | var a = new Date()                                                                                                                                                                                                                                                                                 |
| dblclick                     |                                                                                                                                                                                                                                                                                                    |
| do……while                    | <p>var i = 0</p><p>do{</p><p>    document.write(i)</p><p>    i++</p><p>}while(i<5)</p>                                                                                                                                                                                                             |
| E                            | Math.E //Equal to 2.718281828459045                                                                                                                                                                                                                                                                |
| endsWith                     | "happy".endsWith("y") //Equal to true                                                                                                                                                                                                                                                              |
| entries()                    | <p>arrSet = {a:1,b:2,c:3}</p><p>Object.entries(arrSet) //Equal to \[\["a",1],\["b",2],\["c",3]]</p>                                                                                                                                                                                                |
| eval()                       | eval("1+2") //Equal to 3                                                                                                                                                                                                                                                                           |
| every()                      | \[1,2,3,4,5].every(x => x<4) //Equal to false                                                                                                                                                                                                                                                      |
| exp()                        | Math.exp(20) //Equal to 485165195.4097903                                                                                                                                                                                                                                                          |
| fill()                       | \[1,2,3,4,5].fill("h") //Equal to \["h","h","h","h","h"]                                                                                                                                                                                                                                           |
| find()                       | \[1,2,3,4,5].find(x => x>2) //Equal to 3                                                                                                                                                                                                                                                           |
| findIndex()                  | \[1,2,3,4,5].find(x => x>2) //Equal to 2                                                                                                                                                                                                                                                           |
| flat()                       | \[1,2,3,\[4,5]].flat() //Equal to \[1,2,3,4,5]                                                                                                                                                                                                                                                     |
| floor()                      | Math.floor(2.145) //Equal to 2                                                                                                                                                                                                                                                                     |
| freeze()                     | Object.freeze(obj)                                                                                                                                                                                                                                                                                 |
| forEach()                    | \[1,2,3,4,5].forEach((x,y)=>console.log(y+ "" +x))                                                                                                                                                                                                                                                 |
| for loop                     | for(i=0; i<6; i++){}                                                                                                                                                                                                                                                                               |
| for……in                      |                                                                                                                                                                                                                                                                                                    |
| for……of                      |                                                                                                                                                                                                                                                                                                    |
| from()                       | Array.from("12") //Equal to \["1","2"]                                                                                                                                                                                                                                                             |
| function(){}                 | <p>function(){</p><p>    return "happy new year";</p><p>}</p><p>\Equal to () => "happy new year"</p>                                                                                                                                                                                               |
| getElementById(id)           | document.getElementById("demo")                                                                                                                                                                                                                                                                    |
| getElementsByTagName(name)   | getElementsByTagName("p")                                                                                                                                                                                                                                                                          |
| getElementsByClassName(name) | getElementsByTagName("demo")                                                                                                                                                                                                                                                                       |
| getTime()                    | new Date().getTime() //Equal to time from 1970.1.1                                                                                                                                                                                                                                                 |
| getFullYear()                | new Date().getFullYear() //Equal to 2020                                                                                                                                                                                                                                                           |
| setFullYear()                | new Date().setFullYear(2019) //Equal to 2019yr                                                                                                                                                                                                                                                     |
| getUTCFullYear()             | new Date().getUTCFullYear() //Equal to 2020                                                                                                                                                                                                                                                        |
| setUTCFullYear()             |                                                                                                                                                                                                                                                                                                    |
| getMonth()                   | new Date().getMonth() //Equal to Month -1                                                                                                                                                                                                                                                          |
| setMonth()                   |                                                                                                                                                                                                                                                                                                    |
| getUTCMonth()                |                                                                                                                                                                                                                                                                                                    |
| setUTCMonth()                |                                                                                                                                                                                                                                                                                                    |
| getDate()                    | new Date().getDate() //Equal to today number                                                                                                                                                                                                                                                       |
| setDate()                    |                                                                                                                                                                                                                                                                                                    |
| getNamedItem()               | var x = btn.attributes.getNamedItem("class").value                                                                                                                                                                                                                                                 |
| getUTCDate()                 |                                                                                                                                                                                                                                                                                                    |
| setUTCDate()                 |                                                                                                                                                                                                                                                                                                    |
| getDay()                     | new Date().getDay() //Equal to a week number                                                                                                                                                                                                                                                       |
| setDay()                     |                                                                                                                                                                                                                                                                                                    |
| getUTCDay()                  |                                                                                                                                                                                                                                                                                                    |
| setUTCDay()                  |                                                                                                                                                                                                                                                                                                    |
| getHours()                   | new Date().getHours() //Equal to this hour number                                                                                                                                                                                                                                                  |
| setHours()                   |                                                                                                                                                                                                                                                                                                    |
| getUTCHours()                |                                                                                                                                                                                                                                                                                                    |
| setUTCHours()                |                                                                                                                                                                                                                                                                                                    |
| getMinutes()                 | new Date().getMinutes() //Equal to this minute number                                                                                                                                                                                                                                              |
| setMinutes()                 |                                                                                                                                                                                                                                                                                                    |
| getUTCMinutes()              |                                                                                                                                                                                                                                                                                                    |
| setUTCMinutes()              |                                                                                                                                                                                                                                                                                                    |
| getSeconds()                 | new Date().getSeconds() //Equal to this seconds number                                                                                                                                                                                                                                             |
| setSeconds()                 |                                                                                                                                                                                                                                                                                                    |
| getUTCSeconds()              |                                                                                                                                                                                                                                                                                                    |
| setUTCSeconds()              |                                                                                                                                                                                                                                                                                                    |
| getMilliseconds()            | new Date().getMilliseconds() //Equal to this milliseconds number                                                                                                                                                                                                                                   |
| setMilliseconds()            |                                                                                                                                                                                                                                                                                                    |
| getUTCMilliseconds()         |                                                                                                                                                                                                                                                                                                    |
| setUTCMilliseconds()         |                                                                                                                                                                                                                                                                                                    |
| has()                        |                                                                                                                                                                                                                                                                                                    |
| height                       | screen.height //Equal to screen height                                                                                                                                                                                                                                                             |
| hypot()                      | Math.hypot(3,4) //Equal to 5                                                                                                                                                                                                                                                                       |
| includes()                   | \[1,2,3,4,5].includes(5) //Equal to true                                                                                                                                                                                                                                                           |
| indexOf()                    | "abcde".indexOf("b") //Equal to 1                                                                                                                                                                                                                                                                  |
| Infinity                     |                                                                                                                                                                                                                                                                                                    |
| innerHeight                  | window\.innerHeight //Equal to browser window height                                                                                                                                                                                                                                               |
| innerHTML                    |                                                                                                                                                                                                                                                                                                    |
| innerWidth                   | window\.innerWidth //Equal to browser window width                                                                                                                                                                                                                                                 |
| insertBefore()               | element.insertBefore(para,child);                                                                                                                                                                                                                                                                  |
| isArray()                    | Array.isArray(\[1,2,3,4,5]) //Equal to true                                                                                                                                                                                                                                                        |
| isFinite                     | isFinite(10/0)                                                                                                                                                                                                                                                                                     |
| isInteger()                  | Number.isInteger(10/2) //Equal to true                                                                                                                                                                                                                                                             |
| isNaN()                      | isNaN("123") //Equal to false                                                                                                                                                                                                                                                                      |
| isSafeInteger()              | Number.isSafeInteger("2") //Equal to false                                                                                                                                                                                                                                                         |
| item()                       | var x = a.attributes.item(1).value                                                                                                                                                                                                                                                                 |
| if……else if……                | <p>if(x>1){</p><p>  return true;</p><p>}else{</p><p>  return false;</p><p>}</p>                                                                                                                                                                                                                    |
| join()                       | \[1,2,3,4,5].join("") //Equal to "12345"                                                                                                                                                                                                                                                           |
| lang                         |                                                                                                                                                                                                                                                                                                    |
| language                     | navigator.language                                                                                                                                                                                                                                                                                 |
| languages                    | navigator.languages                                                                                                                                                                                                                                                                                |
| lastIndexOf()                | \[1,2,3,4,5].lastIndexOf(5) //Equal to 4                                                                                                                                                                                                                                                           |
| length                       | \[1,2,3].length //Equal to 3                                                                                                                                                                                                                                                                       |
| let                          | let a = "apple" //not global                                                                                                                                                                                                                                                                       |
| LN2                          | Math.LN2 //Equal to 0.6931471805599453                                                                                                                                                                                                                                                             |
| LN10                         | Math.LN10 //Equal to 2.302585092994046                                                                                                                                                                                                                                                             |
| location.href                | location.href="<https://www.google.com/>"                                                                                                                                                                                                                                                          |
| log()                        | Math.log(2) //Equal to 0.6931471805599453                                                                                                                                                                                                                                                          |
| LOG2E                        | Math.LOG2E //Equal to 1.4426950408889634                                                                                                                                                                                                                                                           |
| LOG10E                       | Math.LOG10E //Equal to 0.4342944819032518                                                                                                                                                                                                                                                          |
| map                          | \[1,2,3,4,5].map(x => x\*2) //Equal to \[2,4,6,8,10]                                                                                                                                                                                                                                               |
| match()                      | "Str".match(/\[a-z]/g) //Equal to \["t","r"]                                                                                                                                                                                                                                                       |
| max                          | Math.max(1,2,3,4,5) //Equal to 5                                                                                                                                                                                                                                                                   |
| nextSibling                  |                                                                                                                                                                                                                                                                                                    |
| nextElementSibling           |                                                                                                                                                                                                                                                                                                    |
| min                          | Math.min(1,2,3,4,5) //Equal to 1                                                                                                                                                                                                                                                                   |
| mousedown                    |                                                                                                                                                                                                                                                                                                    |
| mouseenter                   |                                                                                                                                                                                                                                                                                                    |
| mouseleave                   |                                                                                                                                                                                                                                                                                                    |
| mousemove                    |                                                                                                                                                                                                                                                                                                    |
| mouseover                    |                                                                                                                                                                                                                                                                                                    |
| mouseout                     |                                                                                                                                                                                                                                                                                                    |
| mouseup                      |                                                                                                                                                                                                                                                                                                    |
| moveTo(x,y)                  |                                                                                                                                                                                                                                                                                                    |
| name                         | var a = btn.atrributes.item(0).name                                                                                                                                                                                                                                                                |
| NaN                          |                                                                                                                                                                                                                                                                                                    |
| nodeName                     |                                                                                                                                                                                                                                                                                                    |
| Number()                     | Number("12345") //Equal to 12345                                                                                                                                                                                                                                                                   |
| Object.values()              | <p>const a = { a: 'somestring', b: 42, c: false };</p><p>Object.values(a)</p><p>//Equal to \['somestring', 42, false]</p>                                                                                                                                                                          |
| onblur()                     |                                                                                                                                                                                                                                                                                                    |
| onclick()                    |                                                                                                                                                                                                                                                                                                    |
| onerror()                    |                                                                                                                                                                                                                                                                                                    |
| onkeyup()                    |                                                                                                                                                                                                                                                                                                    |
| onkeydown()                  |                                                                                                                                                                                                                                                                                                    |
| onkeypress()                 |                                                                                                                                                                                                                                                                                                    |
| onfocus()                    |                                                                                                                                                                                                                                                                                                    |
| onload()                     |                                                                                                                                                                                                                                                                                                    |
| onmouseover()                |                                                                                                                                                                                                                                                                                                    |
| onmouseup()                  |                                                                                                                                                                                                                                                                                                    |
| onmousedown()                |                                                                                                                                                                                                                                                                                                    |
| onunload                     |                                                                                                                                                                                                                                                                                                    |
| onpaste                      |                                                                                                                                                                                                                                                                                                    |
| open()                       | window\.open("<https://www.google.com>")                                                                                                                                                                                                                                                           |
| onsubmit()                   |                                                                                                                                                                                                                                                                                                    |
| outerHeight                  | window\.outerHeight //Equal to window\.innerHeight + bar                                                                                                                                                                                                                                           |
| outerWidth                   | window\.outerWidth //Equal to window\.innerHeight + scroll                                                                                                                                                                                                                                         |
| padStart                     | last4Digits.padStart(card.length,"\*")                                                                                                                                                                                                                                                             |
| parseInt()                   | parseInt("2.456") //Equal to 2                                                                                                                                                                                                                                                                     |
| parseFloat()                 | parseFloat("2.456") //Equal to 2.46                                                                                                                                                                                                                                                                |
| pixelDepth                   | screen.pixelDepth                                                                                                                                                                                                                                                                                  |
| PI                           | Math.PI //Equal to 3.14159256                                                                                                                                                                                                                                                                      |
| platform                     | navigator.platform //Equal to System name                                                                                                                                                                                                                                                          |
| pop()                        | \[1,2,3,4,5].pop() //Equal to 5                                                                                                                                                                                                                                                                    |
| pow(x,y)                     | Math.pow(2,3) //Equal to 8                                                                                                                                                                                                                                                                         |
| previousSibling              |                                                                                                                                                                                                                                                                                                    |
| previousElementSibling       |                                                                                                                                                                                                                                                                                                    |
| print()                      | window\.print()                                                                                                                                                                                                                                                                                    |
| product                      | navigator.product                                                                                                                                                                                                                                                                                  |
| prompt()                     | prompt("happy new year")                                                                                                                                                                                                                                                                           |
| push()                       | \[1,2,3,4,5].push("6") //Equal to \[1,2,3,4,5,6]                                                                                                                                                                                                                                                   |
| querySelector()              |                                                                                                                                                                                                                                                                                                    |
| querySelectorAll()           |                                                                                                                                                                                                                                                                                                    |
| reduce()                     | \[1,2,3,4,5].reduce((a,b)=>a\*b) //Equal to 120                                                                                                                                                                                                                                                    |
| reduceRight()                | \[1,2,3,4,5].reduce((a,b)=>a-b) //Equal to -5                                                                                                                                                                                                                                                      |
| random()                     | Math.random() //Equal to range \[0-1]                                                                                                                                                                                                                                                              |
| remove()                     |                                                                                                                                                                                                                                                                                                    |
| removeChild                  |                                                                                                                                                                                                                                                                                                    |
| removeEventListener()        |                                                                                                                                                                                                                                                                                                    |
| removeNamedItem()            | btn.attributes.removeNamedItem("value")                                                                                                                                                                                                                                                            |
| repeat(num)                  | "12".repeat(2) //Equal to "1212"                                                                                                                                                                                                                                                                   |
| replace                      | <p>var a = "Hi World"</p><p>a.replace("Hi","No") //Equal to "No World"</p>                                                                                                                                                                                                                         |
| replaceChild                 |                                                                                                                                                                                                                                                                                                    |
| reverse()                    | \[1,2,3,4,5].reverse() //Equal to \[5,4,3,2,1]                                                                                                                                                                                                                                                     |
| round()                      | Math.round(3.25) //Equal to 3                                                                                                                                                                                                                                                                      |
| Set()                        | var  arr = New Set()                                                                                                                                                                                                                                                                               |
| setInterval()                | setInterval(alert("Hi"),3000) //Equal to alert("Hi") each 3s                                                                                                                                                                                                                                       |
| setNamedItem()               |                                                                                                                                                                                                                                                                                                    |
| setTimeout()                 | setTimeout(alert("Hi"),3000) //Equal to alert("Hi")                                                                                                                                                                                                                                                |
| shift()                      | \[1,2,3,4,5].shift() //Equal to 1                                                                                                                                                                                                                                                                  |
| sin()                        | Math.sin(30) //Equal to -0.9880316240928618                                                                                                                                                                                                                                                        |
| sinh()                       | Math.sinh(30) //Equal to 5343237290762.231                                                                                                                                                                                                                                                         |
| slice()                      | \[1,2,3,4,5].slice(1,2) //Equal to \[2]                                                                                                                                                                                                                                                            |
| some()                       | \[1,2,3,4,5].some(x => x<2) //Equal to true                                                                                                                                                                                                                                                        |
| sort()                       | \[1,3,2,5,4].sort() //Equal to \[1,2,3,4,5]                                                                                                                                                                                                                                                        |
| specified                    | var btn = document.getElementsByTagName("BUTTON")\[0]; var x = btn.getAttributeNode("onclick").specified;                                                                                                                                                                                          |
| splice()                     | \[1,2,3,4,5].splice(2,1) //Equal to \[3]                                                                                                                                                                                                                                                           |
| split()                      | "1234".split("") //Equal to \["1","2","3","4"]                                                                                                                                                                                                                                                     |
| sqrt()                       | Math.sqrt(4) // Equal to 2                                                                                                                                                                                                                                                                         |
| SQRT2                        | Math.SQRT2 //Equal to 1.4142135623730951                                                                                                                                                                                                                                                           |
| SQRT1\_2                     | Math.SQRT1\_2 //Equal to 0.7071067811865476                                                                                                                                                                                                                                                        |
| startsWith                   | "12345".startsWith("1") //Equal to true                                                                                                                                                                                                                                                            |
| String()                     | String(12345) //Equal to "12345"                                                                                                                                                                                                                                                                   |
| switch                       | <p>switch(x){</p><p>  case 0 :</p><p>      return "happy";</p><p>      break;</p><p>}</p>                                                                                                                                                                                                          |
| style.property               |                                                                                                                                                                                                                                                                                                    |
| tan()                        | Math.tan(45) //Equal to 1.6197751905438615                                                                                                                                                                                                                                                         |
| tanh()                       | Math.tanh(-45) //Equal to -1                                                                                                                                                                                                                                                                       |
| toFixed()                    | 1.23456.toFixed(3) //Equal to 1.235                                                                                                                                                                                                                                                                |
| toLowerCase()                | "Happy".toUpperCase() //Equal to "happy"                                                                                                                                                                                                                                                           |
| toString()                   | \[1,2,3,4,5].toString() //Equal to "1,2,3,4,5"                                                                                                                                                                                                                                                     |
| toString(2)                  | <p>var a = 2;</p><p>a.toString(2) //Equal to "10"</p>                                                                                                                                                                                                                                              |
| toString(8)                  | <p>var a = 16;</p><p>a.toString(8) //Equal to "20"</p>                                                                                                                                                                                                                                             |
| toString(16)                 | <p>var a = 15;</p><p>a.toString(16) //Equal to "f"</p>                                                                                                                                                                                                                                             |
| toUpperCase()                | "happy".toUpperCase() //Equal to "HAPPY"                                                                                                                                                                                                                                                           |
| typeof n                     | typeof includes "number","string","boolean", etc                                                                                                                                                                                                                                                   |
| undefined                    | var a !== undefined //Equal to false                                                                                                                                                                                                                                                               |
| unshift()                    | \[1,2,3,4,5].unshift(6) //Equal to \[6,1,2,3,4,5]                                                                                                                                                                                                                                                  |
| userAgent                    | navigator.userAgent                                                                                                                                                                                                                                                                                |
| value                        | var a = btn.atrributes.item(0).value                                                                                                                                                                                                                                                               |
| var                          | var a = "apple" //global                                                                                                                                                                                                                                                                           |
| wheel                        |                                                                                                                                                                                                                                                                                                    |
| while                        |                                                                                                                                                                                                                                                                                                    |
| width                        | screen.width //Equal to screen width                                                                                                                                                                                                                                                               |
| window                       | window\.innerWidth //Equal to browser width                                                                                                                                                                                                                                                        |
| write()                      | document.write("happy new year")                                                                                                                                                                                                                                                                   |
| writeIn()                    | document.writeIn("happy new year")                                                                                                                                                                                                                                                                 |
| +                            | 1+2 //Equal to 3                                                                                                                                                                                                                                                                                   |
| -                            | 1-2 //Equal to -1                                                                                                                                                                                                                                                                                  |
| \*                           | 1\*2 //Equal to 2                                                                                                                                                                                                                                                                                  |
| /                            | 1/2 //Equal to 0.5                                                                                                                                                                                                                                                                                 |
| \*\*                         | 2\*\*2 //Equal to 4                                                                                                                                                                                                                                                                                |
| %                            | 2%1 //Equal to 0                                                                                                                                                                                                                                                                                   |
| ++                           | 2++ OR ++2                                                                                                                                                                                                                                                                                         |
| --                           | 2-- OR --2                                                                                                                                                                                                                                                                                         |
| >=                           | x>=4                                                                                                                                                                                                                                                                                               |
| \~                           | \~5                                                                                                                                                                                                                                                                                                |
| ^                            |                                                                                                                                                                                                                                                                                                    |
| >                            | x>4                                                                                                                                                                                                                                                                                                |
| <                            | x<4                                                                                                                                                                                                                                                                                                |
| <=                           | x<=4                                                                                                                                                                                                                                                                                               |
| <<                           |                                                                                                                                                                                                                                                                                                    |
| >>                           |                                                                                                                                                                                                                                                                                                    |
| >>>                          |                                                                                                                                                                                                                                                                                                    |
| &                            |                                                                                                                                                                                                                                                                                                    |
| &&                           | true && true //Equal to true                                                                                                                                                                                                                                                                       |
| \|                           |                                                                                                                                                                                                                                                                                                    |
| \|\|                         | true \|\| false //Equal to true                                                                                                                                                                                                                                                                    |
| !=                           | true != false //Equal to true                                                                                                                                                                                                                                                                      |
| !==                          | true !== false //Equal to ture                                                                                                                                                                                                                                                                     |
| ==                           | 4=="4" //Equal to true                                                                                                                                                                                                                                                                             |
| ===                          | 4==="4" //Equal to false                                                                                                                                                                                                                                                                           |


# Examples

### Change Random Colors

```
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>canvas</title>
</head>

<body>
	<div id="demo">I love you!</div>
	<button onclick="changeVal();">click me</button>
<script>
		function changeVal(){
			var obj=document.getElementById("demo");
			var r = Math.floor(Math.random()*255);
			var g = Math.floor(Math.random()*255);
			var b = Math.floor(Math.random()*255);
            var color = "#"+r.toString(16)+g.toString(16)+b.toString(16);
			if(obj.innerHTML=="I love you!"){
					obj.innerHTML="I hate you!";
					obj.style.color = color;
				}else if(obj.innerHTML=="I hate you!"){
					obj.innerHTML="I love you!";
					obj.style.color = color;
					}
		}
</script>
</body>
</html>
```


# Reference

网页的动作语言

Examples are better than 1000 words.——一例胜千言

### 引用

\<head>\</head>

\<body>\</body>

\<script>\</script>

```javascript
<script type="text/javascript" src="javascript.js"></script>
```

### 输出

* innerHTML

```javascript
document.getElementById("demo").innerHTML='Hello World!';
```

* document.write()
* window\.alert()
* console.log()
* print()

### 控制

* getElementById("demo")
* getElementsByClassName("demo")
* getElementsByTagName("p")
* querySelectorAll("p.intro")

### 声明

* var
* let
* cost

### 注释

* //单行注释
* /\*多行注释\*/

### 运算符

* \+
* \-
* \*
* \*\*
* /
* %
* ++
* \--
* &&
* ||
* !
* \==
* \===
* !=
* !==
* \>
* <
* \>=
* <=
* ?
* +=
* -=
* \*=
* /=
* %=
* \*\*=

### 函数

```javascript
function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}
```

* 数组：x = \["a","b","c"]
* 物体：x={name:"fiat",model:"modern",color:"white"}

### 字符串处理

* .length
* indexOf()
* lastIndexOf()
* search()
* slice()
* substring()
* substr()
* replace()
* toUpperCase()
* toLowerCase()
* concat()
* trim()
* charAt()
* charCodeAt()
* split()

### 数字

Js语法中，支持数位是15位，以及小数点后17位。

NaN = not a number

isNaN()

数字进制

```javascript
var myNumber = 32;
myNumber.toString(10);  // returns 32
myNumber.toString(32);  // returns 10
myNumber.toString(16);  // returns 20
myNumber.toString(8);   // returns 40
myNumber.toString(2);   // returns 100000
```

数字变成物体

```javascript
var x = new Number(124);
```

* toExponential()
* toFixed()
* toPrecision()

### 数组

```javascript
var cars = ["Saab", "Volvo", "BMW"];||var cars = new Array("Saab", "Volvo", "BMW");
```

* array.foreach()
* array.push()
* array.pop()
* typeof.array
* array.join("\*")
* array.shift()
* array.unshift()
* delete array\[0]
* array.splice(2,0,"apple","orange")
* array.concat(array)
* sort()
* reverse()

调用

```javascript
person.lastName;||person["lastName"];
```

### 时间

* Date(year, month, day, hours, minutes, seconds, milliseconds)
* toUTCString()
* toISOString()
* toDateString()

| getFullYear()     | Get the **year** as a four digit number (yyyy)    |
| ----------------- | ------------------------------------------------- |
| getMonth()        | Get the month as a number (0-11)                  |
| getDate()         | Get the day as a number (1-31)                    |
| getHours()        | Get the hour (0-23)                               |
| getMinutes()      | Get the minute (0-59)                             |
| getSeconds()      | Get the second (0-59)                             |
| getMilliseconds() | Get the millisecond (0-999)                       |
| getTime()         | Get the time (milliseconds since January 1, 1970) |
| getDay()          | Get the weekday as a number (0-6)                 |
| Date.now()        | Get the time. ECMAScript 5.                       |

| Method               | Description                                                 |
| -------------------- | ----------------------------------------------------------- |
| getUTCDate()         | Same as getDate(), but returns the UTC date                 |
| getUTCDay()          | Same as getDay(), but returns the UTC day                   |
| getUTCFullYear()     | Same as getFullYear(), but returns the UTC year             |
| getUTCHours()        | Same as getHours(), but returns the UTC hour                |
| getUTCMilliseconds() | Same as getMilliseconds(), but returns the UTC milliseconds |
| getUTCMinutes()      | Same as getMinutes(), but returns the UTC minutes           |
| getUTCMonth()        | Same as getMonth(), but returns the UTC month               |
| getUTCSeconds()      | Same as getSeconds(), but returns the UTC seconds           |

| Method            | Description                                       |
| ----------------- | ------------------------------------------------- |
| setDate()         | Set the day as a number (1-31)                    |
| setFullYear()     | Set the year (optionally month and day)           |
| setHours()        | Set the hour (0-23)                               |
| setMilliseconds() | Set the milliseconds (0-999)                      |
| setMinutes()      | Set the minutes (0-59)                            |
| setMonth()        | Set the month (0-11)                              |
| setSeconds()      | Set the seconds (0-59)                            |
| setTime()         | Set the time (milliseconds since January 1, 1970) |

### 数学

* Math.PI
* Math.round()
* Math.pow()
* Math.sqrt()
* Math.abs()
* Math.ceil()
* Math.floor()
* Math.sin()
* Math.cos()
* Math.min()
* Math.max()
* Math.random()
* Math.E
* Math.SQRT2
* Math.SQRT1\_2
* Math.LN2
* Math.LN10
* Math.LOG2E
* Math.LOG10E

### 逻辑

### 逻辑

True or False

```javascript
if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}
```

* Boolean()
* variablename = (condition) ? value1:value2&#x20;

```javascript
if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}
```

```javascript
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
```

```javascript
switch (new Date().getDay()) {
  case 6:
    text = "Today is Saturday";
    break;
  case 0:
    text = "Today is Sunday";
    break;
  default:
    text = "Looking forward to the Weekend";
}
```


# Reference

|    Name    |                   Description                  |  Example  |
| :--------: | :--------------------------------------------: | :-------: |
|      g     |                 global boundary                | /\[a-z]/g |
|   globle   |                test g is or not                |           |
|      i     |                case-insensitive                | /\[a-z]/i |
| ignoreCase |                test i is or not                |           |
|      .     |          any character except newline          |    /\*/   |
|     \w     |              word equal to \[A-z]              |    /\w/   |
|     \W     |        not word equal to  \[]\*%$@# etc        |    /\W/   |
|     \d     |              digit equal to \[0-9]             |    /\d/   |
|     \D     | not digit  equal to anything except for \[0-9] |    /\D/   |
|     \s     |                   whitespace                   |    /\s/   |
|     \S     |                 not whitespace                 |    /\S/   |
|   \[ABC]   |    select A, B or C; if it's \[D], select D    |  /\[ABC]/ |
|   \[^ABC]  |       not select A, B or C; select others      | /\[^ABC]/ |
|     \b     |         select a word the last alphabet        |   /ed\b/  |
|     \D     |       select a word not the last alphabet      |   /ed\D/  |
|      ^     |                      start                     |   /^ed/   |
|      $     |                       end                      |   /ed$/   |


# 开篇

学习微信小程序知识与笔记

## 微信小程序是什么

微信小程序是腾讯公司旗下微信推出的一种轻型应用，置于微信之中，随时启用，免去安装，释放空间，总之是一种很方便的形式。

## 微信小程序为什么要建立

* 对用户：方便，快捷，免安装
* 对开发者：赚取广告费，实现人生价值

## 微信小程序如何创建

这一套知识手册与笔记是伯衡君我从零开始（也不算零啦，姑且听之），创建微信小程序的记录和成长。


# 流程

从创建到上传流程

1. 下载微信小程序开发者工具，网址是<https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html>
2. 下载好后安装微信小程序开发者工具
3. 安装完成后，打开，输入之前在微信小程序平台<https://mp.weixin.qq.com/cgi-bin/wx>注册好后获得的AppID，有源码就直接导入，没有源码就新建
4. 调试小程序，确认没有Bug
5. 上传，并在小程序公众平台后台进行审核
6. 审核通过后上线
7. 绑定到自家微信公众号
8. 开通流量主收钱


# 构成

## 不同类型文件

1. `.json` 后缀的 `JSON` 配置文件，JSON 是一种数据格式，并不是编程语言，在小程序中，JSON扮演的静态配置的角色。
2. `.wxml` 后缀的 `WXML` 模板文件， 在小程序中也有同样的角色，其中 `WXML` 充当的就是类似 `HTML` 的角色。打开 `pages/index/index.wxml`，你会看到类似于html的代码
3. `.wxss` 后缀的 `WXSS` 样式文件， `WXSS` 具有 `CSS` 大部分的特性，小程序在 `WXSS` 也做了一些扩充和修改。
4. `.js` 后缀的 `JS` 脚本逻辑文件， 一个服务仅仅只有界面展示是不够的，还需要和用户做交互：响应用户的点击、获取用户的位置等等。在小程序里边，我们就通过编写 `JS` 脚本文件来处理用户的操作。

## 目录结构

| 文件       | 必需 | 作用       |
| -------- | -- | -------- |
| app.js   | 是  | 小程序逻辑    |
| app.json | 是  | 小程序公共配置  |
| app.wxss | 否  | 小程序公共样式表 |

一个小程序页面由四个文件组成，分别是：

| 文件类型 | 必需 | 作用    |
| ---- | -- | ----- |
| js   | 是  | 页面逻辑  |
| wxml | 是  | 页面结构  |
| json | 否  | 页面配置  |
| wxss | 否  | 页面样式表 |

**注意：为了方便开发者减少配置项，描述页面的四个文件必须具有相同的路径与文件名。**

* index.js
* index.wxml
* index.json
* index.wxss


# 框架

小程序开发框架的目标是通过尽可能简单、高效的方式让开发者可以在微信中开发具有原生 APP 体验的服务。

整个小程序框架系统分为两部分：**逻辑层**（App Service）和 **视图层**（View）。小程序提供了自己的视图层描述语言 `WXML` 和 `WXSS`，以及基于 `JavaScript` 的逻辑层框架，并在视图层与逻辑层间提供了数据传输和事件系统，让开发者能够专注于数据与逻辑。

#### 响应的数据绑定 <a href="#xiang-ying-de-shu-ju-bang-ding" id="xiang-ying-de-shu-ju-bang-ding"></a>

框架的核心是一个响应的数据绑定系统，可以让数据与视图非常简单地保持同步。当做数据修改的时候，只需要在逻辑层修改数据，视图层就会做相应的更新。

通过这个简单的例子来看：

在开发者工具中预览效果

```
<!-- This is our View -->
<view> Hello {{name}}! </view>
<button bindtap="changeName"> Click me! </button>
```

```
// This is our App Service.
// This is our data.
var helloData = {
  name: 'Weixin'
}

// Register a Page.
Page({
  data: helloData,
  changeName: function(e) {
    // sent data change to view
    this.setData({
      name: 'MINA'
    })
  }
})
```

* 开发者通过框架将逻辑层数据中的 `name` 与视图层的 `name` 进行了绑定，所以在页面一打开的时候会显示 `Hello Weixin!`；
* 当点击按钮的时候，视图层会发送 `changeName` 的事件给逻辑层，逻辑层找到并执行对应的事件处理函数；
* 回调函数触发后，逻辑层执行 `setData` 的操作，将 `data` 中的 `name` 从 `Weixin` 变为 `MINA`，因为该数据和视图层已经绑定了，从而视图层会自动改变为 `Hello MINA!`。

#### 页面管理 <a href="#ye-mian-guan-li" id="ye-mian-guan-li"></a>

框架 管理了整个**小程序**的页面路由，可以做到页面间的无缝切换，并给以页面完整的生命周期。开发者需要做的只是将页面的数据、方法、生命周期函数注册到 框架 中，其他的一切复杂的操作都交由 框架 处理。

#### 基础组件 <a href="#ji-chu-zu-jian" id="ji-chu-zu-jian"></a>

框架 提供了一套基础的组件，这些组件自带微信风格的样式以及特殊的逻辑，开发者可以通过组合基础组件，创建出强大的**微信小程序** 。

#### 丰富的 API <a href="#feng-fu-de-api" id="feng-fu-de-api"></a>

框架 提供丰富的微信原生 API，可以方便的调起微信提供的能力，如获取用户信息，本地存储，支付功能等。


# 配置

## 全局配置

### **app.json**

小程序根目录下的 `app.json` 文件用来对微信小程序进行全局配置，决定页面文件的路径、窗口表现、设置网络超时时间、设置多 tab 等。

#### entryPagePath <a href="#entrypagepath" id="entrypagepath"></a>

指定小程序的默认启动路径（首页），常见情景是从微信聊天列表页下拉启动、小程序列表启动等。如果不填，将默认为 `pages` 列表的第一项。不支持带页面路径参数。

```
{
  "entryPagePath": "pages/index/index"
}
```

**pages**

```
{
  "pages": ["pages/index/index", "pages/logs/logs"]
}
```

#### window <a href="#window" id="window"></a>

用于设置小程序的状态栏、导航条、标题、窗口背景色。

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MFf2SHaBmDcXNLi-Xxg%2F-MFfTcquvF7xOMkbxBXj%2F1.png?alt=media\&token=43454a6e-16c0-4023-bdc8-b15377cbaf51)

* **navigationBarBackgroundColor** 导航栏背景颜色
* **navigationBarTextStyle** 导航栏标题颜色 两个参数“black”和“white”
* **navigationBarTitleText** 导航栏标题文字内容
* **navigationStyle** 导航栏样式仅支持default和custom
* **backgroundColor** #ffffff
* **backgroundTextStyle**  下拉 loading 的样式，仅支持 `dark` / `light`
* **backgroundColorTop** 顶部窗口的背景色，仅 iOS 支持
* **backgroundColorBottom** 底部窗口的背景色，仅 iOS 支持
* **onReachBottomDistance**
* **enablePullDownRefresh** 页面刷新，true or false
* **pageOrientation** 页面旋转，拥有参数auto/portrait/landscape，其中auto是跟随系统旋转，landscape是固定横屏，portrait是固定竖屏，如果要支持ipad，则需要是使用如下的命令：

```
{
  "resizable": true
}
```

**tap**

如果小程序是一个多 tab 应用（客户端窗口的底部或顶部有 tab 栏可以切换页面），可以通过 tabBar 配置项指定 tab 栏的表现，以及 tab 切换时显示的对应页面。

&#x20;其中 list 接受一个数组，**只能配置最少 2 个、最多 5 个 tab**。tab 按数组的顺序排序，每个项都是一个对象，其属性值如下：

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MFhin4Oy2Mt8ATSdgD4%2F-MFhjuZKNgV7eSQwb7FJ%2Fimage.png?alt=media\&token=5c7390cd-2b4e-4d53-b09b-f17ffdc6b74e)

#### networkTimeout <a href="#networktimeout" id="networktimeout"></a>

各类网络请求的超时时间，单位均为毫秒。

### app.wxss

### app.js

#### App(Object object) <a href="#app-object-object" id="app-object-object"></a>

注册小程序。接受一个 `Object` 参数，其指定小程序的生命周期回调等。

App() 必须在 `app.js` 中调用，必须调用且只能调用一次。不然会出现无法预期的后果。

**参数**

**Object object**

| 属性                   | 类型       | 默认值 | 必填 | 说明                                            | 最低版本   |
| -------------------- | -------- | --- | -- | --------------------------------------------- | ------ |
| **onLaunch**         | function |     | 否  | 生命周期回调——监听小程序初始化。                             |        |
| onShow               | function |     | 否  | 生命周期回调——监听小程序启动或切前台。                          |        |
| onHide               | function |     | 否  | 生命周期回调——监听小程序切后台。                             |        |
| onError              | function |     | 否  | 错误监听函数。                                       |        |
| onPageNotFound       | function |     | 否  | 页面不存在监听函数。                                    | 1.9.90 |
| onUnhandledRejection | function |     | 否  | 未处理的 Promise 拒绝事件监听函数。                        | 2.10.0 |
| onThemeChange        | function |     | 否  | 监听系统主题变化                                      | 2.11.0 |
| 其他                   | any      |     | 否  | 开发者可以添加任意的函数或数据变量到 `Object` 参数中，用 `this` 可以访问 |        |

### Sitemap.json

小程序根目录下的 `sitemap.json` 文件用来配置小程序及其页面是否允许被微信索引。

```
{
  "rules":[{
    "action": "allow",
    "page": "*"
  }]
}
```


# index.wxml+index.js

## 简单绑定

数据绑定使用 Mustache 语法（双大括号）将变量包起来，可以作用于：

#### 内容 <a href="#nei-rong" id="nei-rong"></a>

```
<view> {{ message }} </view>
```

```
Page({
  data: {
    message: 'Hello World!'
  }
})
```

#### 组件属性(需要在双引号之内) <a href="#zu-jian-shu-xing-xu-yao-zai-shuang-yin-hao-zhi-nei" id="zu-jian-shu-xing-xu-yao-zai-shuang-yin-hao-zhi-nei"></a>

```
<view id="item-{{id}}"> </view>
```

```
Page({
  data: {
    id: 0
  }
})
```

#### 控制属性(需要在双引号之内) <a href="#kong-zhi-shu-xing-xu-yao-zai-shuang-yin-hao-zhi-nei" id="kong-zhi-shu-xing-xu-yao-zai-shuang-yin-hao-zhi-nei"></a>

```
<view wx:if="{{condition}}"> </view>
```

```
Page({
  data: {
    condition: true
  }
})
```

#### 关键字(需要在双引号之内) <a href="#guan-jian-zi-xu-yao-zai-shuang-yin-hao-zhi-nei" id="guan-jian-zi-xu-yao-zai-shuang-yin-hao-zhi-nei"></a>

`true`：boolean 类型的 true，代表真值。

`false`： boolean 类型的 false，代表假值。

```
<checkbox checked="{{false}}"> </checkbox>
```

特别注意：不要直接写 `checked="false"`，其计算结果是一个字符串，转成 boolean 类型后代表真值。

### 运算 <a href="#yun-suan" id="yun-suan"></a>

可以在 `{{}}` 内进行简单的运算，支持的有如下几种方式：

#### 三元运算 <a href="#san-yuan-yun-suan" id="san-yuan-yun-suan"></a>

```
<view hidden="{{flag ? true : false}}"> Hidden </view>
```

#### 算数运算 <a href="#suan-shu-yun-suan" id="suan-shu-yun-suan"></a>

```
<view> {{a + b}} + {{c}} + d </view>
```

```
Page({
  data: {
    a: 1,
    b: 2,
    c: 3
  }
})
```

view中的内容为 `3 + 3 + d`。

#### 逻辑判断 <a href="#luo-ji-pan-duan" id="luo-ji-pan-duan"></a>

```
<view wx:if="{{length > 5}}"> </view>
```

#### 字符串运算 <a href="#zi-fu-chuan-yun-suan" id="zi-fu-chuan-yun-suan"></a>

```
<view>{{"hello" + name}}</view>
```

```
Page({
  data:{
    name: 'MINA'
  }
})
```

#### 数据路径运算 <a href="#shu-ju-lu-jing-yun-suan" id="shu-ju-lu-jing-yun-suan"></a>

```
<view>{{object.key}} {{array[0]}}</view>
```

```
Page({
  data: {
    object: {
      key: 'Hello '
    },
    array: ['MINA']
  }
})
```

## 组合

也可以在 Mustache 内直接进行组合，构成新的对象或者数组。

#### 数组 <a href="#shu-zu" id="shu-zu"></a>

```
<view wx:for="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
```

```
Page({
  data: {
    zero: 0
  }
})
```

最终组合成数组`[0, 1, 2, 3, 4]`。

#### 对象 <a href="#dui-xiang" id="dui-xiang"></a>

```
<template is="objectCombine" data="{{for: a, bar: b}}"></template>
```

```
Page({
  data: {
    a: 1,
    b: 2
  }
})
```

最终组合成的对象是 `{for: 1, bar: 2}`

也可以用扩展运算符 `...` 来将一个对象展开

```
<template is="objectCombine" data="{{...obj1, ...obj2, e: 5}}"></template>
```

```
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      c: 3,
      d: 4
    }
  }
})
```

最终组合成的对象是 `{a: 1, b: 2, c: 3, d: 4, e: 5}`。

如果对象的 key 和 value 相同，也可以间接地表达。

```
<template is="objectCombine" data="{{foo, bar}}"></template>
```

```
Page({
  data: {
    foo: 'my-foo',
    bar: 'my-bar'
  }
})
```

最终组合成的对象是 `{foo: 'my-foo', bar:'my-bar'}`。

**注意**：上述方式可以随意组合，但是如有存在变量名相同的情况，后边的会覆盖前面，如：

```
<template is="objectCombine" data="{{...obj1, ...obj2, a, c: 6}}"></template>
```

```
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      b: 3,
      c: 4
    },
    a: 5
  }
})
```

最终组合成的对象是 `{a: 5, b: 3, c: 6}`。

**注意：** 花括号和引号之间如果有空格，将最终被解析成为字符串

```
<view wx:for="{{[1,2,3]}} ">
  {{item}}
</view>
```

等同于

```
<view wx:for="{{[1,2,3] + ' '}}">
  {{item}}
</view>
```

#### wx:for <a href="#wx-for" id="wx-for"></a>

在组件上使用 `wx:for` 控制属性绑定一个数组，即可使用数组中各项的数据重复渲染该组件。

默认数组的当前项的下标变量名默认为 `index`，数组当前项的变量名默认为 `item`

```
<view wx:for="{{array}}">
  {{index}}: {{item.message}}
</view>
```

```
Page({
  data: {
    array: [{
      message: 'foo',
    }, {
      message: 'bar'
    }]
  }
})
```

使用 `wx:for-item` 可以指定数组当前元素的变量名，

使用 `wx:for-index` 可以指定数组当前下标的变量名：

```
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>
```

`wx:for` 也可以嵌套，下边是一个九九乘法表

```
<view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i">
  <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="j">
    <view wx:if="{{i <= j}}">
      {{i}} * {{j}} = {{i * j}}
    </view>
  </view>
</view>
```

#### block wx:for <a href="#block-wx-for" id="block-wx-for"></a>

类似 `block wx:if`，也可以将 `wx:for` 用在`<block/>`标签上，以渲染一个包含多节点的结构块。例如：

```
<block wx:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>
```

#### wx:key <a href="#wx-key" id="wx-key"></a>

如果列表中项目的位置会动态改变或者有新的项目添加到列表中，并且希望列表中的项目保持自己的特征和状态（如 [input](https://developers.weixin.qq.com/miniprogram/dev/component/input.html) 中的输入内容，[switch](https://developers.weixin.qq.com/miniprogram/dev/component/switch.html) 的选中状态），需要使用 `wx:key` 来指定列表中项目的唯一的标识符。

`wx:key` 的值以两种形式提供

1. 字符串，代表在 for 循环的 array 中 item 的某个 property，该 property 的值需要是列表中唯一的字符串或数字，且不能动态改变。
2. 保留关键字 `*this` 代表在 for 循环中的 item 本身，这种表示需要 item 本身是一个唯一的字符串或者数字。

当数据改变触发渲染层重新渲染的时候，会校正带有 key 的组件，框架会确保他们被重新排序，而不是重新创建，以确保使组件保持自身的状态，并且提高列表渲染时的效率。

**如不提供 `wx:key`，会报一个 `warning`， 如果明确知道该列表是静态，或者不必关注其顺序，可以选择忽略。**

**示例代码：**

在开发者工具中预览效果

```
<switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch>
<button bindtap="switch"> Switch </button>
<button bindtap="addToFront"> Add to the front </button>

<switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch>
<button bindtap="addNumberToFront"> Add to the front </button>
```

```
Page({
  data: {
    objectArray: [
      {id: 5, unique: 'unique_5'},
      {id: 4, unique: 'unique_4'},
      {id: 3, unique: 'unique_3'},
      {id: 2, unique: 'unique_2'},
      {id: 1, unique: 'unique_1'},
      {id: 0, unique: 'unique_0'},
    ],
    numberArray: [1, 2, 3, 4]
  },
  switch: function(e) {
    const length = this.data.objectArray.length
    for (let i = 0; i < length; ++i) {
      const x = Math.floor(Math.random() * length)
      const y = Math.floor(Math.random() * length)
      const temp = this.data.objectArray[x]
      this.data.objectArray[x] = this.data.objectArray[y]
      this.data.objectArray[y] = temp
    }
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addToFront: function(e) {
    const length = this.data.objectArray.length
    this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addNumberToFront: function(e){
    this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
    this.setData({
      numberArray: this.data.numberArray
    })
  }
})
```

**注意：**

当 `wx:for` 的值为字符串时，会将字符串解析成字符串数组

```
<view wx:for="array">
  {{item}}
</view>
```

等同于

```
<view wx:for="{{['a','r','r','a','y']}}">
  {{item}}
</view>
```

**注意：** 花括号和引号之间如果有空格，将最终被解析成为字符串

```
<view wx:for="{{[1,2,3]}} ">
  {{item}}
</view>
```

等同于

```
<view wx:for="{{[1,2,3] + ' '}}" >
  {{item}}
</view>
```

## 模板 <a href="#mo-ban" id="mo-ban"></a>

WXML提供模板（template），可以在模板中定义代码片段，然后在不同的地方调用。

#### 定义模板 <a href="#ding-yi-mo-ban" id="ding-yi-mo-ban"></a>

使用 name 属性，作为模板的名字。然后在`<template/>`内定义代码片段，如：

```
<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>
```

#### 使用模板 <a href="#shi-yong-mo-ban" id="shi-yong-mo-ban"></a>

使用 is 属性，声明需要的使用的模板，然后将模板所需要的 data 传入，如：

```
<template is="msgItem" data="{{...item}}"/>
```

```
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})
```

is 属性可以使用 Mustache 语法，来动态决定具体需要渲染哪个模板：

```
<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>
```

#### 模板的作用域 <a href="#mo-ban-de-zuo-yong-yu" id="mo-ban-de-zuo-yong-yu"></a>

模板拥有自己的作用域，只能使用 data 传入的数据以及模板定义文件中定义的 `<wxs />` 模块。

## **引用**

WXML 提供两种文件引用方式`import`和`include`。

#### import <a href="#import" id="import"></a>

`import`可以在该文件中使用目标文件定义的`template`，如：

在 item.wxml 中定义了一个叫`item`的`template`：

```
<!-- item.wxml -->
<template name="item">
  <text>{{text}}</text>
</template>
```

在 index.wxml 中引用了 item.wxml，就可以使用`item`模板：

```
<import src="item.wxml"/>
<template is="item" data="{{text: 'forbar'}}"/>
```

#### import 的作用域 <a href="#import-de-zuo-yong-yu" id="import-de-zuo-yong-yu"></a>

import 有作用域的概念，即只会 import 目标文件中定义的 template，而不会 import 目标文件 import 的 template。

**如：C import B，B import A，在C中可以使用B定义的`template`，在B中可以使用A定义的`template`，但是C不能使用A定义的`template`**。

```
<!-- A.wxml -->
<template name="A">
  <text> A template </text>
</template>
```

```
<!-- B.wxml -->
<import src="a.wxml"/>
<template name="B">
  <text> B template </text>
</template>
```

```
<!-- C.wxml -->
<import src="b.wxml"/>
<template is="A"/>  <!-- Error! Can not use tempalte when not import A. -->
<template is="B"/>
```

#### include <a href="#include" id="include"></a>

`include` 可以将目标文件**除了** `<template/>` `<wxs/>` 外的整个代码引入，相当于是拷贝到 `include` 位置，如：

```
<!-- index.wxml -->
<include src="header.wxml"/>
<view> body </view>
<include src="footer.wxml"/>
```

```
<!-- header.wxml -->
<view> header </view>
```

```
<!-- footer.wxml -->
<view> footer </view>
```


# Button

按钮

## 属性

| 属性                     | 类型          | 默认值          | 必填 | 说明                                                                                           | 最低版本  |
| ---------------------- | ----------- | ------------ | -- | -------------------------------------------------------------------------------------------- | ----- |
| **size**               | string      | default      | 否  | default; mini                                                                                | 1.0.0 |
| **type**               | string      | default      | 否  | primary; default; warn                                                                       | 1.0.0 |
| **plain**              | boolean     | false        | 否  | 按钮是否镂空，背景色透明                                                                                 | 1.0.0 |
| **disabled**           | boolean     | false        | 否  | 是否禁用                                                                                         | 1.0.0 |
| **loading**            | boolean     | false        | 否  | 名称前是否带 loading 图标                                                                            | 1.0.0 |
| form-type              | string      |              | 否  | 用于 form 组件，点击分别会触发 form 组件的 submit/reset 事件                                                  | 1.0.0 |
| open-type              | string      |              | 否  | 微信开放能力                                                                                       | 1.1.0 |
| **hover-class**        | string      | button-hover | 否  | 指定按钮按下去的样式类。当 `hover-class="none"` 时，没有点击态效果                                                 | 1.0.0 |
| hover-stop-propagation | boolean     | false        | 否  | 指定是否阻止本节点的祖先节点出现点击态                                                                          | 1.5.0 |
| hover-start-time       | number      | 20           | 否  | 按住后多久出现点击态，单位毫秒                                                                              | 1.0.0 |
| hover-stay-time        | number      | 70           | 否  | 手指松开后点击态保留时间，单位毫秒                                                                            | 1.0.0 |
| lang                   | string      | en           | 否  | 指定返回用户信息的语言，zh\_CN 简体中文，zh\_TW 繁体中文，en 英文。                                                   | 1.3.0 |
| session-from           | string      |              | 否  | 会话来源，open-type="contact"时有效                                                                  | 1.4.0 |
| send-message-title     | string      | 当前标题         | 否  | 会话内消息卡片标题，open-type="contact"时有效                                                             | 1.5.0 |
| send-message-path      | string      | 当前分享路径       | 否  | 会话内消息卡片点击跳转小程序路径，open-type="contact"时有效                                                      | 1.5.0 |
| send-message-img       | string      | 截图           | 否  | 会话内消息卡片图片，open-type="contact"时有效                                                             | 1.5.0 |
| app-parameter          | string      |              | 否  | 打开 APP 时，向 APP 传递的参数，open-type=launchApp时有效                                                  | 1.9.5 |
| show-message-card      | boolean     | false        | 否  | 是否显示会话内消息卡片，设置此参数为 true，用户进入客服会话会在右下角显示"可能要发送的小程序"提示，用户点击后可以快速发送小程序消息，open-type="contact"时有效 | 1.5.0 |
| bindgetuserinfo        | eventhandle |              | 否  | 用户点击该按钮时，会返回获取到的用户信息，回调的detail数据与wx.getUserInfo返回的一致，open-type="getUserInfo"时有效              | 1.3.0 |
| bindcontact            | eventhandle |              | 否  | 客服消息回调，open-type="contact"时有效                                                                | 1.5.0 |
| bindgetphonenumber     | eventhandle |              | 否  | 获取用户手机号回调，open-type=getPhoneNumber时有效                                                        | 1.2.0 |
| binderror              | eventhandle |              | 否  | 当使用开放能力时，发生错误的回调，open-type=launchApp时有效                                                      | 1.9.5 |
| bindopensetting        | eventhandle |              | 否  | 在打开授权设置页后回调，open-type=openSetting时有效                                                         | 2.0.7 |
| bindlaunchapp          | eventhandle |              | 否  | 打开 APP 成功的回调，open-type=launchApp时有效                                                          | 2.4.4 |


# UserInfo

用户信息

**用户昵称**

```
userInfo.nickName
```

**例子**

```
<view>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </view>
```

**用户头像**

```
userInfo.avatarUrl
```

**例子**

```
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
```

#### number gender <a href="#number-gender" id="number-gender"></a>

用户性别

**gender 的合法值**

| 值 | 说明 | 最低版本 |
| - | -- | ---- |
| 0 | 未知 |      |
| 1 | 男性 |      |
| 2 | 女性 |      |

#### string country <a href="#string-country" id="string-country"></a>

用户所在国家

#### string province <a href="#string-province" id="string-province"></a>

用户所在省份

#### string city <a href="#string-city" id="string-city"></a>

用户所在城市

#### string language <a href="#string-language" id="string-language"></a>

显示 country，province，city 所用的语言

**language 的合法值**

| 值      | 说明   | 最低版本 |
| ------ | ---- | ---- |
| en     | 英文   |      |
| zh\_CN | 简体中文 |      |
| zh\_TW | 繁体中文 |      |


# TabBar

## 例子

```
"tabBar": {
    "color": "#686868",
    "selectedColor": "#47a86c",
    "backgroundColor": "#ffffff",
    "borderStyle": "white",
    "list": [
      {
        "pagePath": "pages/popular/popular",
        "iconPath": "dist/images/popular_icon.png",
        "selectedIconPath": "dist/images/popular_active_icon.png",
        "text": "热映"
      },
      {
        "pagePath": "pages/coming/coming",
        "iconPath": "dist/images/coming_icon.png",
        "selectedIconPath": "dist/images/coming_active_icon.png",
        "text": "待映"
      },
      {
        "pagePath": "pages/top/top",
        "iconPath": "dist/images/top_icon.png",
        "selectedIconPath": "dist/images/top_active_icon.png",
        "text": "口碑"
      },
      {
        "pagePath": "pages/my/my",
        "iconPath": "dist/images/my_icon.png",
        "selectedIconPath": "dist/images/my_active_icon.png",
        "text": "我的"
      }
    ]
  },
```

tabBar是微信小程序页面下选菜单，最多设置5个，超过五个则无法设置。


# Clipboard

剪切板相关代码

## 例子

```
copy: function () {
    const {
      data
    } = this.data;
    wx.setClipboardData({
      data: `data`,
      success(res) {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
```

命令解释：复制当前内容“data”内的数据，并显示复制成功字样。

涉及：

```
wx.setClipboardData
```

设置系统剪贴板的内容。调用成功后，会弹出 toast 提示"内容已复制"，持续 1.5s

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| data     | string   |     | 是  | 剪贴板的内容                   |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

```
wx.showToast
```

显示消息提示框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值       | 必填 | 说明                           | 最低版本                                                                                   |
| -------- | -------- | --------- | -- | ---------------------------- | -------------------------------------------------------------------------------------- |
| title    | string   |           | 是  | 提示的内容                        |                                                                                        |
| icon     | string   | 'success' | 否  | 图标                           |                                                                                        |
| image    | string   |           | 否  | 自定义图标的本地路径，image 的优先级高于 icon | [1.1.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) |
| duration | number   | 1500      | 否  | 提示的延迟时间                      |                                                                                        |
| mask     | boolean  | false     | 否  | 是否显示透明蒙层，防止触摸穿透              |                                                                                        |
| success  | function |           | 否  | 接口调用成功的回调函数                  |                                                                                        |
| fail     | function |           | 否  | 接口调用失败的回调函数                  |                                                                                        |
| complete | function |           | 否  | 接口调用结束的回调函数（调用成功、失败都会执行）     |                                                                                        |

**object.icon 的合法值**

| 值       | 说明                                                                                                                     | 最低版本 |
| ------- | ---------------------------------------------------------------------------------------------------------------------- | ---- |
| success | 显示成功图标，此时 title 文本最多显示 7 个汉字长度                                                                                         |      |
| loading | 显示加载图标，此时 title 文本最多显示 7 个汉字长度                                                                                         |      |
| none    | 不显示图标，此时 title 文本最多可显示两行，[1.9.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)及以上版本支持 |      |

```
wx.getClipboardData
```

获取系统剪贴板的内容

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

**object.success 回调函数**

**参数**

**Object object**

| 属性   | 类型     | 说明     |
| ---- | ------ | ------ |
| data | string | 剪贴板的内容 |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.getClipboardData({
  success (res){
    console.log(res.data)
  }
})
```


# Api

各种接口命令


# 背景

## wx.setBackgroundTextStyle

> 基础库 2.1.0 开始支持，低版本需做兼容处理。

动态设置下拉背景字体、loading 图的样式

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性        | 类型       | 默认值 | 必填 | 说明                       |
| --------- | -------- | --- | -- | ------------------------ |
| textStyle | string   |     | 是  | 下拉背景字体、loading 图的样式。     |
| success   | function |     | 否  | 接口调用成功的回调函数              |
| fail      | function |     | 否  | 接口调用失败的回调函数              |
| complete  | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

**object.textStyle 的合法值**

| 值     | 说明       | 最低版本 |
| ----- | -------- | ---- |
| dark  | dark 样式  |      |
| light | light 样式 |      |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.setBackgroundTextStyle({
  textStyle: 'dark' // 下拉背景字体、loading 图的样式为dark
})
```

## wx.setBackgroundColor <a href="#wx-setbackgroundcolor-object-object" id="wx-setbackgroundcolor-object-object"></a>

> 基础库 2.1.0 开始支持，低版本需做兼容处理。

动态设置窗口的背景色

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性                    | 类型       | 默认值 | 必填 | 说明                           |
| --------------------- | -------- | --- | -- | ---------------------------- |
| backgroundColor       | string   |     | 否  | 窗口的背景色，必须为十六进制颜色值            |
| backgroundColorTop    | string   |     | 否  | 顶部窗口的背景色，必须为十六进制颜色值，仅 iOS 支持 |
| backgroundColorBottom | string   |     | 否  | 底部窗口的背景色，必须为十六进制颜色值，仅 iOS 支持 |
| success               | function |     | 否  | 接口调用成功的回调函数                  |
| fail                  | function |     | 否  | 接口调用失败的回调函数                  |
| complete              | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行）     |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.setBackgroundColor({
  backgroundColor: '#ffffff', // 窗口的背景色为白色
})

wx.setBackgroundColor({
  backgroundColorTop: '#ffffff', // 顶部窗口的背景色为白色
  backgroundColorBottom: '#ffffff', // 底部窗口的背景色为白色
})
```


# 交互

用户使用小程序的反馈

## wx.showToast <a href="#wx-showtoast-object-object" id="wx-showtoast-object-object"></a>

| 属性       | 类型       | 默认值       | 必填 | 说明                           | 最低版本  |
| -------- | -------- | --------- | -- | ---------------------------- | ----- |
| title    | string   |           | 是  | 提示的内容                        |       |
| icon     | string   | 'success' | 否  | 图标                           |       |
| image    | string   |           | 否  | 自定义图标的本地路径，image 的优先级高于 icon | 1.1.0 |
| duration | number   | 1500      | 否  | 提示的延迟时间                      |       |
| mask     | boolean  | false     | 否  | 是否显示透明蒙层，防止触摸穿透              |       |
| success  | function |           | 否  | 接口调用成功的回调函数                  |       |
| fail     | function |           | 否  | 接口调用失败的回调函数                  |       |
| complete | function |           | 否  | 接口调用结束的回调函数（调用成功、失败都会执行）     |       |

**object.icon 的合法值**

| 值       | 说明                                    | 最低版本 |
| ------- | ------------------------------------- | ---- |
| success | 显示成功图标，此时 title 文本最多显示 7 个汉字长度        |      |
| loading | 显示加载图标，此时 title 文本最多显示 7 个汉字长度        |      |
| none    | 不显示图标，此时 title 文本最多可显示两行，1.9.0及以上版本支持 |      |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.showToast({
  title: '成功',
  icon: 'success',
  duration: 2000
})
```

### 注意 <a href="#zhu-yi" id="zhu-yi"></a>

* wx.showLoading 和 wx.showToast 同时只能显示一个
* wx.showToast 应与 wx.hideToast 配对使用

### **呈现效果**

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLsoUUIpuVZfCKz7W7%2F-MGLtnOesFPhTlMmMf6M%2FshowToast.png?alt=media\&token=34971c7a-2509-49a0-9f56-f9acec8048a4)

## wx.hideToast(Object object) <a href="#wx-hidetoast-object-object" id="wx-hidetoast-object-object"></a>

隐藏消息提示框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

### 注意 <a href="#zhu-yi" id="zhu-yi"></a>

* wx.showToast 应与 wx.hideToast 配对使用

## wx.showModal(Object object) <a href="#wx-showmodal-object-object" id="wx-showmodal-object-object"></a>

显示模态对话框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性           | 类型       | 默认值     | 必填 | 说明                          |
| ------------ | -------- | ------- | -- | --------------------------- |
| title        | string   |         | 否  | 提示的标题                       |
| content      | string   |         | 否  | 提示的内容                       |
| showCancel   | boolean  | true    | 否  | 是否显示取消按钮                    |
| cancelText   | string   | '取消'    | 否  | 取消按钮的文字，最多 4 个字符            |
| cancelColor  | string   | #000000 | 否  | 取消按钮的文字颜色，必须是 16 进制格式的颜色字符串 |
| confirmText  | string   | '确定'    | 否  | 确认按钮的文字，最多 4 个字符            |
| confirmColor | string   | #576B95 | 否  | 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串 |
| success      | function |         | 否  | 接口调用成功的回调函数                 |
| fail         | function |         | 否  | 接口调用失败的回调函数                 |
| complete     | function |         | 否  | 接口调用结束的回调函数（调用成功、失败都会执行）    |

**object.success 回调函数**

**参数**

**Object res**

| 属性      | 类型      | 说明                                                  | 最低版本  |
| ------- | ------- | --------------------------------------------------- | ----- |
| confirm | boolean | 为 true 时，表示用户点击了确定按钮                                |       |
| cancel  | boolean | 为 true 时，表示用户点击了取消（用于 Android 系统区分点击蒙层关闭还是点击取消按钮关闭） | 1.1.0 |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success (res) {
    if (res.confirm) {
      console.log('用户点击确定')
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})
```

### 注意 <a href="#zhu-yi" id="zhu-yi"></a>

* Android 6.7.2 以下版本，点击取消或蒙层时，回调 fail, errMsg 为 "fail cancel"；
* Android 6.7.2 及以上版本 和 iOS 点击蒙层不会关闭模态弹窗，所以尽量避免使用「取消」分支中实现业务逻辑

### 呈现效果

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLvLhXZ_SJ_L27yizz%2F-MGLxamyK-PgC1XvDD5f%2Fimage.png?alt=media\&token=421bc2d7-5d94-41bf-9cf8-3a44cc65023f)

## wx.showLoading(Object object) <a href="#wx-showloading-object-object" id="wx-showloading-object-object"></a>

> 基础库 1.1.0 开始支持，低版本需做兼容处理。

显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值   | 必填 | 说明                       |
| -------- | -------- | ----- | -- | ------------------------ |
| title    | string   |       | 是  | 提示的内容                    |
| mask     | boolean  | false | 否  | 是否显示透明蒙层，防止触摸穿透          |
| success  | function |       | 否  | 接口调用成功的回调函数              |
| fail     | function |       | 否  | 接口调用失败的回调函数              |
| complete | function |       | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.showLoading({
  title: '加载中',
})

setTimeout(function () {
  wx.hideLoading()
}, 2000)
```

### 注意 <a href="#zhu-yi" id="zhu-yi"></a>

* wx.showLoading 和 wx.showToast 同时只能显示一个
* wx.showLoading 应与 wx.hideLoading 配对使用

## wx.hideLoading(Object object) <a href="#wx-hideloading-object-object" id="wx-hideloading-object-object"></a>

> 基础库 1.1.0 开始支持，低版本需做兼容处理。

隐藏 loading 提示框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

## wx.showActionSheet(Object object) <a href="#wx-showactionsheet-object-object" id="wx-showactionsheet-object-object"></a>

显示操作菜单

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性        | 类型              | 默认值     | 必填 | 说明                       |
| --------- | --------------- | ------- | -- | ------------------------ |
| itemList  | Array.\<string> |         | 是  | 按钮的文字数组，数组长度最大为 6        |
| itemColor | string          | #000000 | 否  | 按钮的文字颜色                  |
| success   | function        |         | 否  | 接口调用成功的回调函数              |
| fail      | function        |         | 否  | 接口调用失败的回调函数              |
| complete  | function        |         | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

**object.success 回调函数**

**参数**

**Object res**

| 属性       | 类型     | 说明                     |
| -------- | ------ | ---------------------- |
| tapIndex | number | 用户点击的按钮序号，从上到下的顺序，从0开始 |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.showActionSheet({
  itemList: ['A', 'B', 'C'],
  success (res) {
    console.log(res.tapIndex)
  },
  fail (res) {
    console.log(res.errMsg)
  }
})
```

### 注意 <a href="#zhu-yi" id="zhu-yi"></a>

* Android 6.7.2 以下版本，点击取消或蒙层时，回调 fail, errMsg 为 "fail cancel"；
* Android 6.7.2 及以上版本 和 iOS 点击蒙层不会关闭模态弹窗，所以尽量避免使用「取消」分支中实现业务逻辑

### 呈现效果

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLxeOCE1HC4TDGoS7d%2F-MGLzVzncAJDbr8WzssF%2Fimage.png?alt=media\&token=a39ee575-294f-44a6-a52c-8acb41a9338b)

## wx.enableAlertBeforeUnload <a href="#wx-enablealertbeforeunload-object-object" id="wx-enablealertbeforeunload-object-object"></a>

> 基础库 2.12.0 开始支持，低版本需做兼容处理。

开启小程序页面返回询问对话框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| message  | string   |     | 是  | 询问对话框内容                  |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

## wx.disableAlertBeforeUnload(Object object) <a href="#wx-disablealertbeforeunload-object-object" id="wx-disablealertbeforeunload-object-object"></a>

> 基础库 2.12.0 开始支持，低版本需做兼容处理。

关闭小程序页面返回询问对话框

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |


# 导航栏

有关导航栏的一些动画效果

## wx.showNavigationBarLoading <a href="#wx-shownavigationbarloading-object-object" id="wx-shownavigationbarloading-object-object"></a>

在当前页面显示导航条加载动画

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

### 呈现效果

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLz_oYOgvqLh6-FIGD%2F-MGM0RsJeAEmBe3DOjQD%2Fimage.png?alt=media\&token=8c6b6d3c-9d6f-4aae-8069-afeb57fd5399)

## wx.setNavigationBarTitle <a href="#wx-setnavigationbartitle-object-object" id="wx-setnavigationbartitle-object-object"></a>

动态设置当前页面的标题

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| title    | string   |     | 是  | 页面标题                     |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```
wx.setNavigationBarTitle({
  title: '当前页面'
})
```

### 呈现效果

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLz_oYOgvqLh6-FIGD%2F-MGM37aLXb5tGtmoGwvT%2Fimage.png?alt=media\&token=e7f697cb-4db8-4597-b1b3-9e9bf8f76df2)

## wx.setNavigationBarColor <a href="#wx-setnavigationbarcolor-object-object" id="wx-setnavigationbarcolor-object-object"></a>

> 基础库 1.4.0 开始支持，低版本需做兼容处理。

设置页面导航条颜色

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性              | 类型       | 默认值 | 必填 | 说明                                         |
| --------------- | -------- | --- | -- | ------------------------------------------ |
| frontColor      | string   |     | 是  | 前景颜色值，包括按钮、标题、状态栏的颜色，仅支持 #ffffff 和 #000000 |
| backgroundColor | string   |     | 是  | 背景颜色值，有效值为十六进制颜色                           |
| animation       | Object   |     | 否  | 动画效果                                       |
| success         | function |     | 否  | 接口调用成功的回调函数                                |
| fail            | function |     | 否  | 接口调用失败的回调函数                                |
| complete        | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行）                   |

**object.animation 的结构**

| 属性         | 类型     | 默认值      | 必填 | 说明           |
| ---------- | ------ | -------- | -- | ------------ |
| duration   | number | 0        | 否  | 动画变化时间，单位 ms |
| timingFunc | string | 'linear' | 否  | 动画变化方式       |

**object.animation.timingFunc 的合法值**

| 值           | 说明            | 最低版本 |
| ----------- | ------------- | ---- |
| 'linear'    | 动画从头到尾的速度是相同的 |      |
| 'easeIn'    | 动画以低速开始       |      |
| 'easeOut'   | 动画以低速结束       |      |
| 'easeInOut' | 动画以低速开始和结束    |      |

### 示例代码 <a href="#shi-li-dai-ma" id="shi-li-dai-ma"></a>

```

wx.setNavigationBarColor({
  frontColor: '#ffffff',
  backgroundColor: '#ff0000',
  animation: {
    duration: 400,
    timingFunc: 'easeIn'
  }
})
```

### 呈现效果

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGLz_oYOgvqLh6-FIGD%2F-MGM5KWSEWj-YlFGv2wd%2Fimage.png?alt=media\&token=5ece4aa8-a07b-4146-89b6-0bb95fb8a6ad)

## wx.hideNavigationBarLoading <a href="#wx-hidenavigationbarloading-object-object" id="wx-hidenavigationbarloading-object-object"></a>

在当前页面隐藏导航条加载动画

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |

## wx.hideHomeButton <a href="#wx-hidehomebutton-object-object" id="wx-hidehomebutton-object-object"></a>

> 基础库 2.8.3 开始支持，低版本需做兼容处理。

隐藏返回首页按钮。微信7.0.7版本起，当用户打开的小程序最底层页面是非首页时，默认展示“返回首页”按钮，开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏。

### 参数 <a href="#can-shu" id="can-shu"></a>

#### Object object <a href="#object-object" id="object-object"></a>

| 属性       | 类型       | 默认值 | 必填 | 说明                       |
| -------- | -------- | --- | -- | ------------------------ |
| success  | function |     | 否  | 接口调用成功的回调函数              |
| fail     | function |     | 否  | 接口调用失败的回调函数              |
| complete | function |     | 否  | 接口调用结束的回调函数（调用成功、失败都会执行） |


# 标签

wxml文件内涉及到的标签

### icon

> 基础库 1.0.0 开始支持，低版本需做兼容处理。

图标。组件属性的长度单位默认为px，2.4.0起支持传入单位(rpx/px)。

| 属性    | 类型            | 默认值 | 必填 | 说明                                                                                             | 最低版本  |
| ----- | ------------- | --- | -- | ---------------------------------------------------------------------------------------------- | ----- |
| type  | string        |     | 是  | icon的类型，有效值：success, success\_no\_circle, info, warn, waiting, cancel, download, search, clear | 1.0.0 |
| size  | number/string | 23  | 否  | icon的大小                                                                                        | 1.0.0 |
| color | string        |     | 否  | icon的颜色，同css的color                                                                             | 1.0.0 |

![](https://3789401910-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MF_lLv3y87pOLfxROPC%2F-MGXM8QjCwo1PywkdJEu%2F-MGXTE96HuigkdWy2tIK%2Fimage.png?alt=media\&token=6b618c88-a3d5-453f-aa4e-effc74bc1d6e)

### **text**

> 基础库 1.0.0 开始支持，低版本需做兼容处理。

文本。

| 属性          | 类型      | 默认值   | 必填 | 说明                               | 最低版本   |
| ----------- | ------- | ----- | -- | -------------------------------- | ------ |
| selectable  | boolean | false | 否  | 文本是否可选 (已废弃)                     | 1.1.0  |
| user-select | boolean | false | 否  | 文本是否可选，该属性会使文本节点显示为 inline-block | 2.12.1 |
| space       | string  |       | 否  | 显示连续空格                           | 1.4.0  |
| decode      | boolean | false | 否  | 是否解码                             | 1.4.0  |

**space 的合法值**

| 值    | 说明          | 最低版本 |
| ---- | ----------- | ---- |
| ensp | 中文字符空格一半大小  |      |
| emsp | 中文字符空格大小    |      |
| nbsp | 根据字体设置的空格大小 |      |

### Bug & Tip <a href="#bug-tip" id="bug-tip"></a>

1. `tip`: decode可以解析的有 `&nbsp;` `&lt;` `&gt;` `&amp;` `&apos;` `&ensp;` `&emsp;`
2. `tip`: 各个操作系统的空格标准并不一致。
3. `tip`:text 组件内只支持 text 嵌套。
4. `tip`: 除了文本节点以外的其他节点都无法长按选中。
5. `bug`: 基础库版本低于 `2.1.0` 时， text 组件内嵌的 text style 设置可能不会生效。

### Progress

> 基础库 1.0.0 开始支持，低版本需做兼容处理。

进度条。组件属性的长度单位默认为px，2.4.0起支持传入单位(rpx/px)。

| 属性              | 类型            | 默认值       | 必填 | 说明                                    | 最低版本  |
| --------------- | ------------- | --------- | -- | ------------------------------------- | ----- |
| percent         | number        |           | 否  | 百分比0\~100                             | 1.0.0 |
| show-info       | boolean       | false     | 否  | 在进度条右侧显示百分比                           | 1.0.0 |
| border-radius   | number/string | 0         | 否  | 圆角大小                                  | 2.3.1 |
| font-size       | number/string | 16        | 否  | 右侧百分比字体大小                             | 2.3.1 |
| stroke-width    | number/string | 6         | 否  | 进度条线的宽度                               | 1.0.0 |
| color           | string        | #09BB07   | 否  | 进度条颜色（请使用activeColor）                 | 1.0.0 |
| activeColor     | string        | #09BB07   | 否  | 已选择的进度条的颜色                            | 1.0.0 |
| backgroundColor | string        | #EBEBEB   | 否  | 未选择的进度条的颜色                            | 1.0.0 |
| active          | boolean       | false     | 否  | 进度条从左往右的动画                            | 1.0.0 |
| active-mode     | string        | backwards | 否  | backwards: 动画从头播；forwards：动画从上次结束点接着播 | 1.7.0 |
| duration        | number        | 30        | 否  | 进度增加1%所需毫秒数                           | 2.8.2 |
| bindactiveend   | eventhandle   |           | 否  | 动画完成事件                                | 2.4.1 |

### rich-text

> 基础库 1.4.0 开始支持，低版本需做兼容处理。

富文本。

| 属性    | 类型           | 默认值 | 必填 | 说明               | 最低版本  |
| ----- | ------------ | --- | -- | ---------------- | ----- |
| nodes | array/string | \[] | 否  | 节点列表/HTML String | 1.4.0 |
| space | string       |     | 否  | 显示连续空格           | 2.4.1 |

**space 的合法值**

| 值    | 说明          | 最低版本 |
| ---- | ----------- | ---- |
| ensp | 中文字符空格一半大小  |      |
| emsp | 中文字符空格大小    |      |
| nbsp | 根据字体设置的空格大小 |      |

### nodes <a href="#nodes" id="nodes"></a>

现支持两种节点，通过type来区分，分别是元素节点和文本节点，默认是元素节点，在富文本区域里显示的HTML节点 *元素节点：type = node*\*

| 属性       | 说明    | 类型     | 必填 | 备注                       |
| -------- | ----- | ------ | -- | ------------------------ |
| name     | 标签名   | string | 是  | 支持部分受信任的 HTML 节点         |
| attrs    | 属性    | object | 否  | 支持部分受信任的属性，遵循 Pascal 命名法 |
| children | 子节点列表 | array  | 否  | 结构和 nodes 一致             |

*文本节点：type = text*\*

| 属性   | 说明 | 类型     | 必填 | 备注         |
| ---- | -- | ------ | -- | ---------- |
| text | 文本 | string | 是  | 支持entities |

### 受信任的HTML节点及属性 <a href="#shou-xin-ren-de-html-jie-dian-ji-shu-xing" id="shou-xin-ren-de-html-jie-dian-ji-shu-xing"></a>

全局支持class和style属性，**不支持id属性**。

| 节点         | 属性                           |
| ---------- | ---------------------------- |
| a          |                              |
| abbr       |                              |
| address    |                              |
| article    |                              |
| aside      |                              |
| b          |                              |
| bdi        |                              |
| bdo        | dir                          |
| big        |                              |
| blockquote |                              |
| br         |                              |
| caption    |                              |
| center     |                              |
| cite       |                              |
| code       |                              |
| col        | span，width                   |
| colgroup   | span，width                   |
| dd         |                              |
| del        |                              |
| div        |                              |
| dl         |                              |
| dt         |                              |
| em         |                              |
| fieldset   |                              |
| font       |                              |
| footer     |                              |
| h1         |                              |
| h2         |                              |
| h3         |                              |
| h4         |                              |
| h5         |                              |
| h6         |                              |
| header     |                              |
| hr         |                              |
| i          |                              |
| img        | alt，src，height，width         |
| ins        |                              |
| label      |                              |
| legend     |                              |
| li         |                              |
| mark       |                              |
| nav        |                              |
| ol         | start，type                   |
| p          |                              |
| pre        |                              |
| q          |                              |
| rt         |                              |
| ruby       |                              |
| s          |                              |
| section    |                              |
| small      |                              |
| span       |                              |
| strong     |                              |
| sub        |                              |
| sup        |                              |
| table      | width                        |
| tbody      |                              |
| td         | colspan，height，rowspan，width |
| tfoot      |                              |
| th         | colspan，height，rowspan，width |
| thead      |                              |
| tr         | colspan，height，rowspan，width |
| tt         |                              |
| u          |                              |
| ul         |                              |

### Bug & Tip <a href="#bug-tip" id="bug-tip"></a>

1. `tip`: nodes 不推荐使用 String 类型，性能会有所下降。
2. `tip`: `rich-text` 组件内屏蔽所有节点的事件。
3. `tip`: attrs 属性不支持 id ，支持 class 。
4. `tip`: name 属性大小写不敏感。
5. `tip`: 如果使用了不受信任的HTML节点，该节点及其所有子节点将会被移除。
6. `tip`: img 标签仅支持网络图片。
7. `tip`: 如果在自定义组件中使用 `rich-text` 组件，那么仅自定义组件的 wxss 样式对 `rich-text` 中的 class 生效。


