<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> div{width: 100px;height: 100px;border: 1px solid #333;margin-bottom: 30px;} </style> </head> <body> <div id='qw' style='background:blue'></div> <img src="images/1.jpg" alt="" id='im'> <script type='text/javascript'> var a=document.getElementById('im'); 3種方法屬性設置 (1)屬性設置 // 1.節點對象.屬性名=屬性值; // 注意:特殊屬性須要發生名稱變化,例如:class--->className for--->htmlFor // 2.node.setAttribute(屬性名,屬性值) // 注意:節點屬性名與HTML屬性名一致 // 3.node[屬性名]=屬性值 // 注意:特殊屬性須要發生名稱變化,例如:class--->className for--->htmlFor // 1)種. // a.src='images/2.jpg'; // 2)種. 屬性名 屬性值 // a.setAttribute('src','images/2.jpg'); // 3)種. // a['src']='images/2.jpg'; // 3種屬性獲取 // (2)屬性的獲取 // 1. 節點對象.屬性名 // 2. node.getAttribute(屬性名) // 3. node[屬性名] // 1)種. console.log(a.src);//絕對路徑 // 2)種 console.log(a.getAttribute('src'));//相對路徑 // 3)種 console.log(a['src']);//絕對路徑 // DOM樣式的獲取: // (1)只能取出行內樣式,不能取出樣式表樣式 // node.style.樣式名 // (2)取出其它樣式 // window.getComputedStyle(節點對象,null) // 返回值:style對象 var ac=document.getElementById('qw'); var b=window.getComputedStyle(ac,null).width; console.log(b);//輸出值是100px /* DOM中樣式的修改 節點對象.style.樣式名=值; HTML中樣式的名稱在DOM中一樣有效, 注意:特殊樣式,須要改變 text-align ----> textAlign 去掉-,從第二個單詞開始首字母大寫 */ var o=document.getElementById('qw'); o.style.background='red'; //爲對象新增屬性,能夠隨意新增屬性(bc也能夠是一個屬性,本身定義的) a.bc='hello'; alert(a.bc); console.log(a.bc); </script> </body> </html>