# Javascript # 基礎介紹及教學 ![GDG On Campus - Horizontal - White - Red - 2](https://hackmd.io/_uploads/SyHR7VGM1x.png) --- ## Javascript 的用途 ---- 一個網頁最基本是由 HTML、CSS 和 Javascript 所構成 而 Javascript 是其中負責網頁"行為"的程式語言 ---- Javascript 會在我們使用網頁的期間,根據指令改變呈現出來的東西或物件的屬性。 ---- ### HTML 及 CSS 快速介紹 ![image](https://hackmd.io/_uploads/BkNZODeGyl.png =215x)![image](https://hackmd.io/_uploads/H1lyuveGJx.png =150x) ---- HTML是藉由Tag在網頁中置入物件 CSS則是一個集合了HTML各個物件的展示方式 ![image](https://hackmd.io/_uploads/H1whOPxzJx.png =300x)![image](https://hackmd.io/_uploads/HJXA_PeMke.png =450x) --- ## Javascript 的發展 ---- * 1995年誕生,由 Netscape 為了自己的瀏覽器發明,並取名 Live Script * 2009年ES5誕生並開始獨佔市場,成為最廣泛使用且成熟的程式語言 * 2015年ES6完成,成為目前主要採用的版本 --- ## Javascript 運行基礎流程 ---- 1. 選定目標 2. 接收事件 3. 執行函式 --- ## Javascript 的 Value Types 和 Variables ---- ### Value Types * number * boolean * string * null * undefined ---- ### Variables * let * const ---- ```javascript= let a = 10 const b = 5 console.log(a) //10 console.log(b) //5 a += 1 console.log(a) //11 b += 1 console.log(b) //error ``` ---- ### typeof ```javascript= let names = 'Name', age = 18 let nullVariable = null, undefinedVariable console.log(typeof names) //string console.log(typeof age) //number names = (age == 18) console.log(typeof names) // boolean console.log(typeof nullVariable) //object console.log(typeof undefinedVariable) //undefined ``` ---- ### NAN * not a number * not equal to anything * isNAN() ---- ### parseInt parseFloat * 把字串轉換成int或float * 無法轉換會回傳NAN --- ## Javascript 的 Reference Types ---- ### Reference Types * Object * Array * Function ---- #### object.property #### object['property'] #### object.method() ---- ```javascript= function Date(month, date) { this.month = month this.date = date } Date.prototype.printOut = function() { console.log('Data: ' + this.month + '/' + this.date) } let data = new Date(11, 28) console.log(data.month) console.log(data['date']) data.printOut() ``` ---- ```javascript= class Date { constructor(month, date) { this.month = month this.date = date } printOut() { console.log('Data: ' + this.month + '/' + this.date) } } let data = new Date(11, 28) console.log(data.month) console.log(data['date']) data.printOut() ``` ---- String * length * toUpperCase() * substr(a, b) * indexOf(a) ---- Array ```javascript= let arr1 = new Array() //empty let arr2 = new Array(1) //1 undefined element let arr3 = [1, '2', true] for (i of arr3) { console.log(i) } ``` ---- * concat() * join() * pop() * push() * reverse() * shift() * slice() * splice() * sort() * toString() * unshift() --- ## Practice 1 製作一個 object(class) 存圓柱體的相關資料 包含屬性 radius, height 和2個函式分別計算體積和底面圓周長 PI ($\pi$) 取 3.14 用 console.log 輸出 ---- HTML ```html= <html> <head> <title>Practice 1</title> <link rel="stylesheet" href="style.css"> <meta charset="utf-8"> <script src="script.js" defer></script> </head> <body></body> </html> ``` CSS ```css= /*no css code required*/ ``` --- ## Javascript 的 Target Selector ---- ### DOM (Document Object Model) * Element * Attr * Text * Comment * Document * DocumentType ---- ```html= <tag id='id' class='class' name='nameValue' attr='attrValue'> </tag> ``` Selector * getElementsByTagName() * getElementById() * getElementsByName() * getElementsByClassName() ---- * querySelector() 用 CSS 的 Selector tag #id .class [name='nameValue'] [attr='attrValue'] ---- ### forEach ```javascript= Array.prototype.forEach.call(object, function(element) { //function //run for every element in the object }) ``` --- ### 計時器 setInterval() 每隔一段時間執行一次 ```javascript= let func = setInterval(function() { //function }, delay); clearInterval(func) ``` setTimeout() 隔一段時間後執行 ```javascript= let func = setTimeout(function() { //function }, delay); clearTimeout(func) ``` ---- ### Math ---- ```javascript= Math.random() //random number within [0,1) Math.abs() Math.floor() Math.ceil() Math.max() Math.min() Math.sin() Math.sinh() Math.asin() ``` --- ## Javascript 的 Event ---- ### Events * load * change * click * mousedown/mouseup * mousemove/mouseenter/mouseleave * keypress/keydown/keyup ---- ### EventListener ---- ```javascript= element.addEventListener('event', function() { //function }) ``` ```javascript= let selectedBall = document.getElementById('ball') selectedBall.addEventListener('click', function() { this.style.backgroundColor = 'red' }) ``` ---- ```javascript= document.addEventListener('mousedown', function(event) { console.log(event.button) //0:Left 1:Middle 2:Right }) ``` ```javascript= document.addEventListener('keypress', function(event) { console.log(event.key) console.log(event.code) console.log(event.charCode) }) ``` --- ## Practice 2 製作一個 EventListener 讓使用者滑鼠進入物件時顏色改變 離開時再變回來 ---- HTML ```html= <html> <head> <title>Practice 1</title> <link rel="stylesheet" href="style.css"> <meta charset="utf-8"> <script src="script.js" defer></script> </head> <body> <div id='red1' class='balls redBall'></div> <div id='red2' class='balls redBall'></div> <div id='blue1' class='balls blueBall'></div> <div id='blue2' class='balls blueBall'></div> <div id='blue3' class='balls blueBall'></div> </body> </html> ``` ---- CSS ```css= * { margin: 0; overflow: hidden; } body { width: 100vw; min-height: 100vh; justify-content: center; align-items: center; display: grid; grid-template-columns: repeat(5, 1fr); } div { margin: auto; width: 10vw; height: 10vw; border-radius: 50%; } .redBall { background: red; } .blueBall { background: blue; } ``` --- ## Element Properties ---- ### Style ```javascript= element.style.property console.log(element.style) ``` ---- ### Attributes ```javascript= element.getAttribute('attr') element.hasAttribute('attr') element.hasAttributes() element.setAttribute('attr', 'attrValue') element.removeAttribute('attr') ``` ---- ### HTML text ```html= <div class='innerTextHTML'>Hello</div> ``` ```javascript= element.innerHTML element.outerHTML let element = document.querySelector('.innerTextHTML') console.log(element.innerHTML) //Hello console.log(element.outerHTML) //<div class="innerTextHTML">Hello</div> ``` ---- ### Child & Sibling ```html= <div class='lv1'> <div class='lv2'> <div class='lv3'></div> <div class='lv3'></div> </div> <div class='lv2'> <div class='lv3'></div> </div> </div> ``` ---- ```javascript= element.childNodes //list of childs element.firstChild element.lastChild element.appendChild(newElement) element.removeChild(childElement) element.replaceChild(newElement, childElement) ``` ```javascript= element.nextSibling element.previousSibling element.after(newElement) ``` ---- ### Create new element ```javascript= let element = document.getElementById('id') let newElement = document.createElement('tag') let newElementText = document.createTextNode('text') element.appendChild(newElement) element.after(newElement) ``` ---- ### Remove element ```javascript= let element = document.getElementById('id') element.remove() //remove itself ``` ```javascript= let element = document.getElementById('id') let childElement = element.childNodes[0] let originalElement = element.childNodes[1] let newElement = document.createElement('tag') element.removeChild(childElement) element.replaceChild(newElement, originalElement) ``` --- ## Practice 3 製作一個在空白鍵按下後啟動的程式 並使指示燈變紅色 讓使用這只要在指定範圍內(淺藍色方框)按下滑鼠 就根據按下的按鍵執行不同的函式 * 滑鼠左鍵: 在滑鼠的位置生成一個紫色的圓形 * 滑鼠右鍵: 在方框內的隨機位置生成一個白色圓形 * 滑鼠滾輪: 清除方框內的所有圓形 再次按下空白鍵已停止該程式及將指示燈變回綠色 ---- HTML ```html= <html> <head> <title>Practice 1</title> <link rel="stylesheet" href="style.css"> <meta charset="utf-8"> <script src="script.js" defer></script> </head> <body> <div id='indicator'></div> <div id='container'></div> </body> </html> ``` ---- CSS ```css= * { margin: 0; overflow: hidden; } body { width: 100vw; min-height: 100vh; justify-content: center; align-items: center; display: grid; grid-template-columns: 1fr 5fr 1fr; grid-template-rows: 2fr 5fr 1fr; } #indicator { grid-column: 2/3; margin: auto; width: 60%; height: 16vh; background-color: rgb(47, 195, 47); border-radius: 8vh; } #container { grid-column: 2/3; grid-row: 2/3; margin: auto; width: 96%; height: 96%; background-color: rgb(108, 154, 220); border-width: 3px; border-style: solid; border-color:rgb(17, 26, 93) } .balls { position: absolute; width: 20px; height: 20px; border-radius: 50%; } .purpleBall { background: rgb(148, 18, 139); } .whiteBall { background: rgb(255, 255, 255); } ```
{"title":"Javascript","description":"#Javascript","contributors":"[{\"id\":\"20f4c891-00e8-482d-b480-2246b9b151d0\",\"add\":11746,\"del\":1731}]"}
    269 views