DOM對象**1.屬性** docment.title 返回當前文檔的標題docment.URL 返迴文檔完整的URLdocument.bgColor 背景色document.fgColor 前景色 **2.方法** 2.1 document.getElementById(“elementID”); ...
DOM對象
**1.屬性**
docment.title 返回當前文檔的標題
docment.URL 返迴文檔完整的URL
document.bgColor 背景色
document.fgColor 前景色
**2.方法**
2.1 document.getElementById(“elementID”);
返回帶有指定標簽名的對象的集合
參數值 “*” 返迴文檔的所有元素
返回的集合對象擁有 length 屬性 , 並且可以通過 ****Index 來訪問集合中的元素
2.2 document.getElementsByTagName(“tagname”);
返回帶有指定標簽名的對象的集合
參數值 “*” 返迴文檔的所有元素
返回的集合對象擁有 length 屬性 , 並且可以通過 Index 來訪問集合中的元素
2.3 document.getElementsByName(“name”);
返回帶有指定名稱的對象的集合
返回的集合對象擁有 length 屬性 , 並且可以通過 Index 來訪問集合中的元素
存在相容性問題 ( 該方法適用於表單操作 )IE瀏覽器中, 如果 name 存在於 form 表單中,可以正常使用,但是如果出現在例如 div 元素中,則不能正常返回值,原因是name並不是div的標準屬性
2.4 document.getElementsByClassName(“classname”);
返迴文檔中所有指定類名的元素集合
返回的集合對象擁有 length 屬性 , 並且可以通過 Index 來訪問集合中的元素
小結:除了ID都是返回的對象的集合,可以用Index來訪問集合中的元素。
**3.對象的集合**
3.1 all
所有對象的集合 , 常用來做相容性判斷
3.2 forms
所有 form 表單集合
console.log(document.forms.length);
通過 index 來訪問表單對象
document.forms[0];
通過表單的 name 屬性來訪問表單對象
document.forms["name"];
**4.操作元素的內容**
4.1 innerHTML:
設置或獲取標簽對中的內容 ( 識別 HTML )
4.2 innerText:
獲取文字內容 ( IE ) textContent: 獲取文字內容 (FF,chrom)
**5.屬性操作**
5.1 直接操作
object.attr = value ( 獲取和設置 )
5.2 方法
獲取 : object.getAttribute(“attr”)
設置 : 對象 .setAttribute(“attr”, “value”)
**6.樣式操作**
6.1 行內樣式
設置和獲取 : object.style.attr
類似hover效果。
html:
<a id="one" href="#" style="color: red;background-color: blue; padding: 3px;"> 跳轉 </a>
javascript:
(function() {
var one = document.getElementById("one");
one.onmouseover = function() {
this.style.color = "blue";
this.style.backgroundColor = "red";
};
one.onmouseout = function() {
this.style.color = "red";
this.style.backgroundColor = "blue";
};
}());
**6.2 css 層疊樣式**
通過 className 修改樣式
獲取或修改某個屬性的值 ( 相容性問題 )
document.styleSheets 返回樣式表的集合
document.styleSheets[index].rules / document.styleSheets[index].cssRules 返回樣式表中選擇器的集合
document.styleSheets[index].rules[index].style.attr 查找樣式表中的樣式屬性 (ie chrom)
document.styleSheets[index].cssRules[index].style.attr 查找樣式表中的樣式屬性 (firefox)
動態添加或刪除
document.styleSheets[index].insertRule(“selector{attr:value}”, index);
document.styleSheets[index].deleteRule(index);
document.styleSheets[index].addRule(“selector”,”attr:value”, index);
document.styleSheets[index].removeRule(index);
6.3 獲取最終樣式 ( 只能獲取 , 不能操作 )
object.currentStyle.attr ( IE )
window.getComputedStyle(object,null).attr ( W3C )
6.4 獲得元素尺寸 ( 可直接運算 )
clientWidth/clientHeight: 元素可視部分的高度和寬度 (width + padding)
offsetWidth/offsetHeight: 元素實際的高度和寬度 (width+padding+border)