標籤彙整:DOM

DOM animation

window object

  • show the page url → window.location.href
  • show user agent → window.navigator.userAgent
  • show the width and height of the page → window.outerWidth/window.outerHeight
  • window is a global variable, also can use outerWiidth instead of window.outerWidth

setInterval(callback function, time)

  • window.clearInterval(callback function, time)
  • window.setInterval(the name of setInterval you want to cancel)
  • window.setTimer(callback function, time)
  • parseFloat()
h3 the world will end in 
  span#countdown 500
  |  seconds !
var countdown = document.querySelector("#countdown");

var countItDown = function() {
  //parseFloat(): turn string into number
  //stop negative timing, stop this animation when it come to zero
  var currentTime = parseFloat(countdown.textContent);
  if (currentTime > 0) {
    countdown.textContent = currentTime - 1;
  } else {
    //window.clearInterval(): stop excute the function
    window.clearInterval(timer);
  };

};

//call this function on a interval
//在一定期間内執行function
//window.setInterval(callback function, time)
//the functino will execute every 1 second
var timer = window.setInterval(countItDown, 1000);
//add: window.setTimerout: only excute 1 time

Display

the world will end in 500 seconds !

高效能的動畫語法:requestAnimationFrame()

搭配new Date().getTime()設定速率
img#pic(src="https://goo.gl/o3iBL0")
var pic = document.querySelector("#pic");
pic.style.width = "10px"
  //make the speed slow down
var startTime = new Date().getTime();
var makeItBig = function() {
  var currentTime = new Date().getTime();
  //10 the start width
  //20 speed
  //currentTime-startTime: the millisecond passed
  var newWidth = (10 + ((currentTime - startTime) / 1000) * 20);
  pic.style.width = newWidth + "px";
  //"10px" is a string
  //pic.style.width=parseFloat(pic.style.width)+1+"px";
  //call animation
  if (newWidth < 300) {
    window.requestAnimationFrame(makeItBig);
  }

};

makeItBig();

//method: setInterval
//30frames of 1 second
//window.setInterval(makeItBig,1000/30);
Display

DOM event

jQuery版
監聽事件一覽

連結事件與動作:addEventListener()

點擊觸發:”click”

method 1

button#btn try to click
//1 select the id
var btn = document.querySelector("#btn");
//2 event function
//event listener function(callback function)
//only the event happens, we call this function
//if we want to call it when webpage loads, we use
//clicked();
//()→means callling the function
//if we dont't have ()→just mention it
var clicked = function() {
  btn.textContent = "you clicked me!!"
};

//3 combine 1 and 2
//addEvenetListener(event, function)
//clicked()→×, clicked→○
//"clicked" means mouse click
btn.addEventListener("click", clicked);

method 2 : anonymous function

var btn = document.querySelector("#btn");


btn.addEventListener("click",
  //anonymous function
  function(){
    btn.textContent="you clicked me!!";
});
Display

滑鼠滑過互動:”mousemove”, clientX, clientY

div#box
  img#face(src="https://goo.gl/EZspJs" width=300)
.beard
  width: 5px
  height: 5px
  background-color: #000
  border-radius: 100%
  position: absolute
//"mousemove"
//clientX
//clientY

//select the id
var face=document.querySelector("#face");

//draw beard
var draw=function(evt){
  var beard=document.createElement("div");
  beard.className="beard";
  document.querySelector("#box").appendChild(beard);
  beard.style.top=evt.clientY+"px";
  beard.style.left=evt.clientX+"px";
};

//combine
face.addEventListener("mousemove",draw);

Display

value:儲存表單資料

label What's your name
  input#name
br
label What's languague you speak
  select#lang
    option(value="en") English
    option(value="jp") Japanese
    option(value="ch") Chinese
br
button#btn click me
#message
//select elements
var btn=document.querySelector("#btn");
//event listener function
var clickBtn=function(){
  //add user's name
  //value: to find what user typed
  //to store the name value when btn clicked
  var name=document.querySelector("#name").value;
  //store the lang
  var lang=document.querySelector("#lang").value;
  var greeting
  if(lang==="en"){
    greeting="hallo "+name;
  }else if(lang==="jp"){
    greeting="こんにちは "+name;
  }else {
    greeting="你好 "+name;
  }
  //var greeting="Heyaz "+name;
  document.querySelector("#message").textContent=greeting
};
//combine
btn.addEventListener("click",clickBtn);
Display



preventDefault():取消預設屬性

.bgm
  a#music(href="https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3") START MUSIC
//progressive enhancement

//select
var music=document.querySelector("#music");

var musicClick = function(e){
  //cancel default behavior
  //preventDefault(): let it not turn to the new mp3 url
  e.preventDefault();
  //create audio tag
  var audio=document.createElement("audio");
  audio.src="https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3";
  audio.autoplay="true";
  document.querySelector("#bgm").appendChild(audio);
};

//combine
music.addEventListener("click",musicClick);

Display

DOM修改

jQuery版

改變標籤内的屬性

img#img(src="https://scontent-tpe1-1.xx.fbcdn.net/v/t1.0-9/993735_563618560401443_1458385305_n.jpg?oh=61017324bae69919cf7a8bab9346429b&oe=58A0C30A" width="300")

 

//後面不接innerHTML,指定要改變的屬性
document.querySelector("#img").width="150"

Display
原本的寬度是300px

加了JS後,寬度改寫成150px

CSS query

  1. 用CSS找html屬性
  2. 再用JS抓CSS找到的東西
p
  a(href="https://www.wikiwand.com/en/Dog" target="_blank") this is a link
//選取所有href裡面有Dog的東西
//對大小寫敏感
a[href*="Dog"]
  //可以改顏色等確認有沒有選到
  color: blue
  //這步驟熟了就可以不用寫css了,直接寫JS一樣選的到
  
//後面不接innerHTML,指定要改變的屬性
//反斜線抵銷特殊字元
var href_ch = document.querySelectorAll("a[href*=\"Dog\"]");

//雖然只有一個link但因為是陣列形式所以必須這樣寫
for(i=0;i<href_ch.length;i++){
 href_ch[i].href="https://www.wikiwand.com/en/Cat" ;
}
Display
本來的狗狗超連結變成貓咪的連結了

改變CSS

h3 some text
//用style選擇改寫css
//js不支援-,所以要拿掉-,下一個單字改大寫
document.querySelector("h3").style.backgroundColor="#DDD8C4"

Display

some text

修改了css,背景變成褐色了

新增class

h4#h4 some text
.h4
 color: rgb(221, 216, 196)
 font-size: 26px
//+=新增,用=會變成取代class
document.querySelector("#h4").className+="h4"
//另一種寫法(支援新型瀏覽器)
//document.querySelector("#h4").classList.add("h4")

some text

添加了class,文字變成褐色了

新增id

h4.h4 some text
#h4
 color: #90a955
 font-size: 26px
//+=新增,用=會變成取代id
document.querySelectorAll(".h4")[0].id+="h4"

Display

some text

字變成綠色了

改内容文字 textContent=””

h3#title My Cute Dog
document.querySelector("#title").textContent="Catsss"

Display

Catsss

My Cute Dog變成Catsss了

innerHTML進階:裡面填tags

h3#title My Cute Dog
document.querySelector("#title").innerHTML="<em>Catsss</em>"

Display

Catsss

My Cute Dog不但變成Catsss了,還加了斜體

create tag: createElement()&appendChild()

div#div
 h3 MY PET
 p Moko is a cute dog, she is my best friend
//add new tag
var new_img=document.createElement("img");

//add attr
new_img.src="https://scontent-tpe1-1.xx.fbcdn.net/v/t35.0-12/14572506_1297653033664655_1042535654_o.jpg?oh=b89ff559e5f91a1a67826ce4e41eb373&oe=581AF1D8";
new_img.width=300;

new_img.alt="dog MOKO"
//add content: textContent=""
//add class: className+=""/classList.add();


//put on your img: appendChild()
//appendChild 在#div之下新增一個child,排在#div裡面所有child最後面
document.body.appendChild(new_img);

Display

MY PET

Moko is a cute dog, she is my best friend

用js增加一張圖片

應用練習:取代字串

h1 About My 
 span.dog Dog
hr
p moko is a beautiful 
 span.dog dog
 br
 | she is my best 
 span.dog dog
 | friend
 br
 | I love my 
 span.dog dog
var dog = document.querySelectorAll("p .dog");


for (var i=0;i<dog.length;i++){
  //create em tag
  var em=document.createElement("em");

  //add content
  //也可以用textContent
  //textNode,最枝微末節的tag裡面的文字内容
  var em_text =document.createTextNode(" CAT");
  
  //消除原本的dog
  dog[i].innerHTML="";
  
  //em is parent of em_text
  em.appendChild(em_text);

  //dog is the parent of em
  dog[i].appendChild(em);

  }

Display

About My CAT


moko is a beautiful CAT
she is my best CAT friend
I love my CAT
把dog都改成cat

DOM

意思

Document Object Mode
JavaScript找到html/css的節點node,並且控制或改變它

<h3>Document Object Mode</h3>
<p>has existed</p>
//document 總體變數
//找到網頁文件下的body tag 裡面包住的所有字,然後換成
document.body.innerHTML="ERRRRRRRRRRRRR!"
Display

如果沒有JavaScript的話,會長這樣

Document Object Mode

has existed

但是JavaScript改變了内容,所以變成

ERRRRRRRRRRRRR!

使用選擇器改變html, css内容

ID selector: getElementById()

div
 h1#heading My Dogs
 p Animal is the best friend
//getElementById("ID") ID選擇器,裡面不用加#
document.getElementById("heading").innerHTML="Your Cats"
Display

Your Cats

My Dogs變成Your Cats了

Animal is the best friend

tag selector: getElementsByTagName()

不像id只會出現一個,tag會出現很多次,所以要用迴圈批量命名

div
 p
 | The domestic 
 span.animal dog
 | is known as man's best friend. The 
 span.animal dog
 | was the first domesticated animal and has been widely kept as a working, hunting, and pet companion. According to recent coarse estimates, there are currently between 700 million and one billion 
 span.animal dog
 | s, making them the most abundant predators in the world.
//先命名變數
//注意element"s"
var span_els = document.getElementsByTagName("span");
//抓下來的tag是陣列形式(HTML collection)
//所以要這樣寫才能在console看到
//console.log(span_els[0])

//用迴圈批量改
for (var i = 0; i < span_els.length; i++) {
 span_els[i].innerHTML = "cat";
}
Display

The domestic cat is known as man’s best friend. The cat was the first domesticated animal and has been widely kept as a working, hunting, and pet companion. According to recent coarse estimates, there are currently between 700 million and one billion cats, making them the most abundant predators in the world.

dog全部變成cat了

class selector: getElementsByClassName()

class一樣會出現很多次,也要迴圈命名

div
 p
 | The domestic 
 span.animal dog
 | is known as man's best friend. The 
 span.animal dog
 | was the first domesticated animal and has been widely kept as a working, hunting, and pet companion. According to recent coarse estimates, there are currently between 700 million and one billion 
 span.animal dog
 | s, making them the most abundant predators in the world.
var animal_els = document.getElementsByClassName("animal");

for (var i = 0; i < animal_els.length; i++) {
 animal_els[i].innerHTML = "cat";
}
Display

The domestic cat is known as man’s best friend. The cat was the first domesticated animal and has been widely kept as a working, hunting, and pet companion. According to recent coarse estimates, there are currently between 700 million and one billion cats, making them the most abundant predators in the world.

dog全部變成cat了

其他選擇法:querySelector()

任意選擇一個class, tag, id…等任何元素
jQuery也是用此法選擇
效能比getElemetBy法好,但需要較新瀏覽器支援

div 
 h3#h3 Hey this's my dog
 p it's name is moko
//id的話要加#,class的話加.
document.querySelector("#h3").innerHTML=("Your cat is so cool")
Display

Your cat is so cool

標題變成cat了

it’s name is moko

可以往下選擇小孩元素:querySelectorAll()

選CSS的話母親跟小孩中間要加空格

div
 h1 About My 
 span.pet Dog
 hr
 p moko is a beautiful 
 span.pet dog
 br
 | she is my best 
 span.pet dog
 | friend
 br
 | I love my 
 span.pet dog
var pet_els=document.querySelectorAll("p .pet")
//得出一個node list,跟陣列很像
for(var i=0;i<pet_els.length;i++){
 pet_els[i].innerHTML="CAT"
}
Display

About My dog


moko is a beautiful CAT
she is my best CAT friend
I love my CAT

只有内文的dog被換成cat

進階:querySelector() 與 querySelectorAll 的差異

querySelector 只能選取單一元素,以及他的HTML部分而已
querySelectorAll 可以選取複數元素【陣列】,以及該元素所有資訊【nodeList】
※如果想抓到 nodeList 資訊的話,必須使用  querySelectorAll選擇器(不論想抓單一或複數元素)

.text SOME TEXT
var qs=document.querySelector(".text");
console.log(qs); //<div class="text">SOME TEXT</div>
//↑回報字串

var qsa=document.querySelectorAll(".text");
console.log(qsa); //出現複雜的nodeList,一個一個點開來看可以找到很多資訊

//注意:如果想要再網頁中使用 nodeList ,必須先轉換成陣列才可以

中括號:指定屬性

※querySelector、querySelectorAll 都可以使用

p(color="green") title1
p(color="green") title2
p(color="green") title3
p(color="green") title4
p(color="blue") title5
p(color="blue") title6
p(color="blue") title7
p(color="blue") title8
const greens=document.querySelectorAll("p[color='green']");

greens.forEach(green => green.style.color="#5aad6f");

Display

title1

title2

title3

title4

title5

title6

title7

title8

選取HTML屬性(Attribute)

用法一:不指定內容

h1(data-color="red") Red
h1 Blue
h1 Orange
h1 Green
document.querySelector("h1[data-color]") 
//"<h1 data-color='red'>Red</h1>"

如果data-color只有一個的話,querySelector會選到唯一的一個,但若data-color有數個的話,querySelector只會選到第一個

要讓第二個data-color也被選到的話,要使用querySelectorAll,並指定index

h1(data-color="red") Red
h1(data-color="blue") Blue
h1(data-color="orange") Orange
h1(data-color="Green") Green
document.querySelector("h1[data-color]") //"<h1 data-color='red'>Red</h1>"
document.querySelectorAll("h1[data-color]")[1]//"<h1 data-color='blue'>Blue</h1>"

用法二:指定名稱

h1(data-color="red") Red
h1(data-color="blue") Blue
h1(data-color="orange") Orange
h1(data-color="Green") Green
document.querySelector("h1[data-color='red']") //"<h1 data-color='red'>Red</h1>"