Javascript - 從零開始 Day2

第二天

範例 9

  1. 流程
    (1) 捲動 => 那一塊 => addClass
    (2) 按鈕 => 那一塊 => 捲動(1)
    (3) 回到頂端 => 捲最上(1)
  2. 卷軸往下 1px 內容往上 1px
  3. offset(全域座標) vs position(區塊座標)
  4. 寬高比較
    (1) width(),height() DOM 內容寬高
    (2) innerWidth(),innerHeight() DOM 內容寬高+padding 寬高
    (3) outerWidth(),outerHeight() DOM 內容寬高+padding 寬高+border 寬高
    (4) outerWidth(true),outerHeight(true) DOM 內容寬高+padding 寬高+border 寬高+margin 寬高
  5. function 中斷不能用 break 要用 return false

jQuery

1
2
3
4
// 點goTop一下
$("#goTop").click();
// 做click事件偵聽
$("#goTop").click(function() {});

***forEach vs each
forEach((obj,index)=>{})
each((index,obj)=>{})

eq : 等於

動畫 : animate

  1. normal: animate(動畫屬性,時間,加減速,完成後的 FUNCTION)
  2. advence: animate(動畫屬性,設定)

*建議用第二種用法,需要打到比較多屬性英文,幫助更多了解及記憶

*事件偵聽要先有偵聽,之後才能觸發

JQUERY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(function() {
// 請輸入你的程式
let $contents = $("#container > section");
let completeHandler = function() {
console.log("OK");
};

// 做click事件偵聽
$("#goTop")
.click(function() {
// 1.normal: animate(動畫屬性,時間,加減速,完成後的FUNCTION)
// 2.advence: animate(動畫屬性,設定)
// $("html,body").animate({ scrollTop: 0 }, 1000, "linear", completeHandler);
$("html,body").animate(
{ scrollTop: 0 },
{
duration: 1000,
easing: "linear"
// complete: completeHandler
}
);
})
.click();
// 點goTop一下(觸發)
// $("#goTop").click();

$(window)
.scroll(function() {
let top = $(window).scrollTop() + $("#nav").outerHeight(true);
let bottom = $(window).scrollTop() + $(window).height();
let target = 0;
$contents.each((index, section) => {
let sectionTop = $(section).offset().top;
let secBottom = $(section).offset().top + $(section).outerHeight(true);
// width() ,height() DOM 內容寬高
// innerWidth() ,innerHeight() DOM 內容寬高 + padding 寬高
// outerWidth() ,outerHeight() DOM 內容寬高 + padding 寬高 + border 寬高

// outerWidth(true) ,outerHeight(true)
// DOM 內容寬高 + padding 寬高 + border 寬高 + margin 寬高

if (sectionTop >= top && secBottom >= top) {
target = index;
// 中斷
return false;
}
});
$(".nav > a")
.removeClass("active")
.eq(target)
.addClass("active");
})
.scroll();
$(".nav > a").click(function() {
// this => 按到的按鈕 => js對象
// $(this) => jq對象
let index = $(this).index(); // 按鈕編號
let $target = $("#container > section").eq(index);
let position = $target.offset().top - $("#nav").outerHeight(true);
$("html,body").animate({ scrollTop: position }, 500);
});

// $(".nav a")
// .eq(0)
// .addClass("active");
})();