javascript_DOM 編程藝術學習筆記(七)
一、元素的樣式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.onload = function(){
var para = document.getElementById("example");
alert(typeof para.nodeName);
alert(typeof para.style);
alert(para.style.color);
alert(para.style.fontSize)
alert(para.style.fontFamily);
}
</script>
</head>
<body>
<p id="example" style="font-size:1em;color:#999999;font-family:'Arial',sans-serif;">
An Example of a paragraph
</p>
</body>
</html>
1、獲取元素的樣式
element.style
2、獲取元素的顏色
element.style.color
3、獲取元素的文字大小
樣式是font-size,但是javascript不能這樣寫,會認爲是減號,必須要用駝峯式寫法。因此獲取的方式是:element.style.fontSize,其他的類似的也是這種寫法。
4、設置元素的樣式:
如:設置元素的顏色,右邊的值都是字符串,必須要用引號,單引號和雙引號都行。
element.style.color = "red"
5、這種通過style獲取樣式的方法,只能用於內嵌樣式,也就是說放在標籤內部的樣式。如果通過樣式表,或者放在<head>標籤之中都不能獲取。
二、獲取元素相鄰的節點
1、獲取下一個元素節點
/**
* 獲取元素節點
* @param {[element]} node [元素節點]
* @return {[element]} [元素節點]
*/
function getNextElement (node) {
if(node.nodeType == 1){ // nodeType等於1,表示是元素節點
return node;
}
if(node.nextSibling){ // 確定有下一個節點
return getNextElement(node.nextSibling);
}
return null;
}