3分鐘:第 3 章 Javascript
_05
Javascript
是什麼?
JavaScript 是一種基於物件的腳本程式語言。更詳細的內容請參考 維基百科 。
我們在上一章了解了
CSS
。透過
CSS
,我們製作出了
具有特定屬性的事物
。現在,我們要告訴這個傢伙
該做些什麼
。
_06 當點擊按鈕時,顯示提示視窗。
HTML
<div class="button" id="id_button">Button</div>
CSS
<style>
.button {
background-color:green;
color:white;
width:auto;
height:auto;
}
</style>
Javascript
<script>
document.getElementById("id_button").addEventListener("click",function(){
alert("hello world");
});
</script>
將上述內容匯集到
.html
檔案中,如下所示:
<!Documen HTML>
<html>
<head>
<style>
.button {
background-color:green;
color:white;
width:auto;
height:auto;
}
</style>
</head>
<body>
<div class="button" id="id_button">Button</div>
<script>
document.getElementById("id_button").addEventListener("click",function(){
alert("hello world");
});
</script>
</body>
</html>
上述內容是一個範例,當點擊該
div
標籤時,會顯示
'hello world'
字串。
使用 JavaScript,可以透過特定標籤的
id
、
class
等,賦予該標籤特定的動作。
不僅是點擊,還可以賦予
mouseover
、
mouseout
等滑鼠事件的動作。
_07 更改按鈕的屬性。
HTML
<div class="button" id="id_button">Button</div>
CSS
<style>
.button {
background-color:green;
color:white;
width:auto;
height:auto;
}
</style>
Javascript
<script>
// 將 id_button 的顏色變更為紅色。
document.getElementById("id_button").style.color="red";
</script>
_08 停用按鈕的樣式表。
HTML
<div class="button" id="id_button">Button</div>
CSS
<style id="btn_css">
.button {
background-color:green;
color:white;
width:auto;
height:auto;
}
</style>
Javascript
<script>
// 停用文件中 ID 為 btn_css 的樣式。
document.getElementById("btn_css").disabled = true;
</script>
今天我們簡單地了解了 JavaScript。我所介紹的 JavaScript,您可以將其視為一種
氛圍
而非
學習
。
以下是關於 JavaScript 的簡單學習資源:
事實上,JavaScript 確實是一種需要
學習
才能正確使用的腳本語言。當您學習 JavaScript 時,會聽到
ECMAScript
這個詞。
將該詞理解為 JavaScript 的
標準化
腳本語言會比較容易。
cf.
之後編寫 JavaScript 時,可能會在腳本開頭看到use strict這句話。
這表示該腳本遵循標準,而遵循標準意味著該腳本設計為在多種瀏覽器中都能以相同方式運作。
總結
- JavaScript 讓 HTML 變得生動。
- JavaScript 可以更改套用到
document
的屬性值。
- JavaScript 可以自主更改
document
的標籤。
- 今天稍微體驗到的 JavaScript 大約只佔 1%。其餘 99% 真的無窮無盡。
3 分鐘預告
- 如果從頭開始學習所有 JavaScript 再來使用似乎太困難了,有沒有更簡單的使用方法呢?