一、一般的,查找一個元素節點用到的語句:
1、根據元素的id來查找 ---》elementId
document.getElementById(elementId);
2、根據元素的class屬性 ---》className
document.getElementsByClassName(className);
3、根據元素(即標籤)的標籤名 ---》 tagName
document.getElementsByTagName(tagName);
4、根據選擇器secletor,(這個與標籤名有些類似)
document.querySelector(tagName);
document.querySelectorAll(tagName);
注:
document.querySelector(""); 是在DOM樹下找到的第一個與之匹配的元素節點
document.querySelectorAll(""); 是在DOM樹下全部與之匹配的元素節點
二、js 的運行是至頂向下的
三、JavaScript HTML 事件
1、onload 和 onunload 事件:會在用戶進入或離開頁面時被觸發,(即 onload:頁面加載時 onunload:關閉頁面時觸發)
window.onload=function(){ 代碼 };
頁面加載的時候,觸發該語句。
2、onchange事件:常結合對輸入字段的驗證來使用(有點像元素節點獲得焦點後,再失去焦點。這個過程結束後,觸發事件)
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
//a-z(ascii碼):97-122
if(x.value>='a'&&x.value<='z'){
x.value=x.value.toUpperCase();
}else
//x.value>'A'&&x.value<'Z' A-Z(ascii碼):65-90
x.value=x.value.toLowerCase();
}
</script>
</head>
<body>
請輸入英文字符:<input type="text" id="fname" onchange="myFunction()">
<p>當您離開輸入字段時,會觸發將輸入文本轉換爲大寫或小寫的函數。</p>
</body>
</html>
這個例子是大小寫字母轉換,當你輸入一個字母后,會觸發onchange=“myFunction()”,輸入文本轉換字母大小寫
3、onmouseover 和 onmouseout 事件:可用於在用戶的鼠標移至HTML元素上方或移出元素時觸發函數
onmouseover事件觸發是,需要改變樣式的話,可以用element:hover{ css樣式 } (element可以是元素,id,class屬性)
4、onmousedown、onmouseup 以及 onclick 事件
onmousedown:點擊鼠標按鈕時觸發
onmouseup:鬆開鼠標按鈕時觸發
onclick:完成鼠標點擊時觸發
(好像平常的頁面也不經常看到onmousedown 和 onmouseup 事件。用得最多的就是 onclick 事件)
5、onfocus 和onblur (一般用在文本輸入框)
onfocus:元素獲取焦點時觸發
onblur:元素失去焦點時觸發
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x){
x.style.background="yellow";
}
function blurFunction(y){
y.style.background="white";
document.querySelector("input").value="";
}
</script>
</head>
<body>
請輸入英文字符:<input type="text" onfocus="myFunction(this)" onblur="blurFunction(this)">
<br>
<p>當輸入字段獲得焦點時,會觸發改變背景顏色的函數。</p>
<p>當輸入字段失去焦點時,會觸發改變背景顏色的函數,並且將文本框內的文本清空。</p>
</body>
</html>
當你點擊文本框的時候,獲取焦點;當你點擊其他地方的時候,文本框失去焦點。