直接在文章編輯器寫CSS,JS的方法

方法

  1. 文章編輯→點選編輯視窗右上角的「文字」標籤
  2. 找到要套用CSS/JS目標元素HTML碼,上方鍵入<style>標籤,將CSS碼貼上去,並且刪除所有空白行與註解
  3. 在目標元素HTML碼下方鍵入<script>標籤,將原生JS碼貼上去,並且刪除所有空白行與註解

jQuery解法

上述方法可以成功執行CSS/原生JS碼的情況,但JS使用到jQuery的情況下,就要用特殊解法

 

wordpress本身就會引jQuery,所以撰寫時可以省去加入src

 

//不用寫這個
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

 

WordPress的文字編輯過濾器會預設編成文章<p>,所以直接使用jQuery在網頁顯示上會變成這種情況

 

<p>
 <script>
 //jQuery程式碼
 </script>
</p>
解決:打開佈景主題的編輯器Editor,在functions.php貼上這一段碼,取消文字編輯過濾器,然後我們就可以得到正常的 script tag

 

/*Toggle wpautop*/
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
如果佈景主題只找到style.css,表示此佈景為子佈景,修改母佈景的function.php後再套用回原來的子佈景就可以執行!

 

接下來,回到文章,在jQuery外面包一層ready(),變成這樣

 

<script>
jQuery(document).ready(function( $ ){
//jQuery程式碼
});
</script>
刪除 jQuery 程式碼所有空白行,註解,並且確保程式碼簡潔
大功告成!

 

沒有使用外掛寫jQuery的範例

JavaScript 基礎

Number

%:除法取餘數

>43%10
3

String

\t:tab空格

>"I have a\tapple"
"I have a   apple"

display “” in output

>""I have a \"apple\"""
"I have a "apple""

\n:斷行

>"I have a \napple"
"I have a 
apple"

.length:計算字數(含空格)

>"I have an apple".length
15
//第一個字元為1,數字的算法跟charAt()不同,所以總數會比charAt()多1

Methods

.charAt():傳來字串中的第某個字

  1. 第一個字元為0,從0開始算
  2. 空格算一個字元
  3. 符號也算一個字元
>var sentence="I have an apple"
>sentence.charAt(3)
"a"
//0:"I"
//1:""
//2:"h"
//3:"a"

Others

內引js檔
<script src="../scripts/trains.js"></script>
  1. 起點是index.html (沒寫出來)
  2. 【..】表示跳到上面資料夾
  3. scripts/ 找到 scripts 資料夾裡面的 trains.js

 

Image Slider

結構

  1. 相框slider:overflow: hidden
  2. 相片平放卷軸holder:橫長結構,長度必須包覆所有圖片
  3. 相片
  4. 動畫:transform: translateX(負的相片寬度)
.slider
 .holder
  .pic
  .pic
  .pic
  .pic
  .pic
  .pic
  .pic
  .pic
$s-width: 1200px
$s-height: 600px

.slider
  width: $s-width
  height: $s-height
  border: 1px solid #000
  overflow: hidden
  
.holder
  width: $s-width*8
  position: relative
  left: 0
  animation: scroller 20s infinite
  
.pic
  width: $s-width
  height: $s-height
  float: left
  position: relative
  overflow: hidden
  background-position: center center
  background-size: cover
  &:nth-child(1)
    background-image: url("https://goo.gl/ro6eWb")
  &:nth-child(2)
    background-image: url("https://goo.gl/kgH2tw")
  &:nth-child(3)
    background-image: url("https://goo.gl/0dx76j")
  &:nth-child(4)
    background-image: url("https://goo.gl/7wvNvb")
  &:nth-child(5)
    background-image: url("https://goo.gl/3940uB")
  &:nth-child(6)
    background-image: url("https://goo.gl/rmI6Fy")
  &:nth-child(7)
    background-image: url("https://goo.gl/z9G2Wb")
  &:nth-child(8)
    background-image: url("https://goo.gl/QEG93R")

@keyframes scroller
  12.5%
    transform: translateX(0)
  25%
    transform: translateX(-$s-width)
  37.5%
    transform: translateX(-$s-width*2)
  50%
    transform: translateX(-$s-width*3)
  62.5%
    transform: translateX(-$s-width*4)
  75%
    transform: translateX(-$s-width*5)
  87.5%
    transform: translateX(-$s-width*6)
  100%
    transform: translateX(-$s-width*7)

Display

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