自定義屬性
<div id="box" stuId = "1">張三</div><a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >删除</a>
<script>
var box = document.getElementById('box');
console.log(box.stuId); //當通路對象中不存在的屬性,傳回undefined
</script>
在chrome中不能使用上面方式擷取标簽的自定義屬性。
- getAttribute()擷取标簽行内屬性
- setArrribute()設定标簽行内屬性
- removeAttribute()移除标簽行内屬性
- 與element.屬性的差別:上述三個方法用于擷取任意的行内屬性。
<div id="box" stuId = "1">張三</div><a href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >删除</a>
<script>
//擷取标簽自定義屬性
console.log(box.getAttribute('stuId'));
//設定标簽的自定義屬性
box.setAttribute('test','hello');
//設定标簽本身具有的屬性
box.setAttribute('class','bg');
//移除屬性
box.removeAttribute('test');
box.removeAttribute('class');
// 不可以設定标簽的自定義屬性,但是box對象本身具有了abc屬性
box.abc = 'hello';
console.log(box.abc);
樣式操作和類名操作
①使用style方式設定的樣式在标簽行内(注:通過樣式屬性設定寬高、位置的屬性類型是字元串,需加上px)。
this.style擷取的僅僅是标簽的style中設定的樣式,如果标簽沒有設定style、屬性,此時擷取的都是空字元。
//this.style 擷取的僅僅是标簽的style中設定的樣式屬性,如果标簽沒有設定style屬性,此時擷取的都是空字元串
console.log(this.style);
修改标簽 的className屬性相當于直接修改标簽的類名
【注】如果設定的樣式屬性比較多時,推薦使用class,反之推薦使用style。
var box = document.getElementById('box');
//樣式操作
//1 設定類樣式
box.className='box';
//2 設定行内樣式style
console.dir(box);
box.style.width = '200px';
box.style.height = '200px';
box.style.backgroundColor = 'red';
//cssText 擷取标簽的style屬性中的字元串
console.log(box.style.cssText);
【注意】
類名操作中,元素.className的方式可能會覆寫原有的類選擇器。使用時不能替換掉原有的類選擇器。
QRShow.className="show"; //會覆寫原有的類選擇器,可通過下面方法解決
QRShow.className="QRShow show" //方法一
QRShow.className = QRShow.className.replace('hide','show'); //方法二
【擴充】
選擇器的優先級
為同一個元素設定多個樣式時,此時哪個樣式生效由選擇器的優先級确定
· | 内聯樣式 | id選擇器 | 類和僞類選擇器 | 元素選擇器 | 統配選擇器 | 繼承的樣式 |
優先級 | 1000 | 100 | 10 | 1 | 無 |
- 當一個選擇器中含有多個選擇器時,需要将所有的選擇器的優先級進行相加,然後再進行比較,優先級高的優先顯示,選擇器的計算不會超過其最大的數量級(10個id選擇器的優先級不能達到1000)
- 分組選擇器(并集選擇器)的優先級單獨計算,不會相加。
- 樣式後面加!important,該樣式擷取最高優先級,内聯樣式不能加!important屬性。
- 樣式相同的誰在下面執行誰(樣式的覆寫)。
節點操作
元素節點和屬性節點
<div id="box"></div>
<script>
//元素節點
var box = document.getElementById('box');
//nodeName 标簽的名稱
//nodeType 節點的類型 1 元素節點
//nodeValue 當是元素節點的時候nodeValue始終是null
console.dir(box);
//屬性節點 ---節點就是對象
//擷取屬性節點
//nodeName 屬性的名稱
//nodeType 節點的類型 2 屬性節點
//nodeValue 屬性的值
var arr = box.getAttributeNode('id');
console.dir(arr);
</script>
nodeType節點的類型
- 元素節點
- 屬性節點
- 文本節點
nodeName :節點的名稱
nodeValue:節點值(元素節點的nodeValue始終是null)