之所以attribute和property容易混倄在一起的原因是,很多attribute节点还有一个相对应的property属性,比如上面的div元素的id和class既是attribute,也有对应的property,不管使用哪种方法都可以访问和修改。
但是对于自定义的attribute节点,或者自定义property,两者就没有关系了。(不信可以自己试试,我试过了,但对于IE6-7来说,没有区分attribute和property)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img id="oImg" src="" data-src="img/1.jpg" alt="" gameid="800" width="300">
</body>
<script>
var oImg = document.getElementById("oImg");
document.onclick = function(){
oImg.src = oImg.getAttribute("data-src");
}
oImg.width=500;
//oImg.setAttribute("width",400)
console.log(oImg.width,oImg.getAttribute("width"))//300 "300"
//console.log(oImg.gameid,oImg.getAttribute("gameid"))//undefined 800
//attribute为html内容 property是名值对属性
//console.log(oImg.id,oImg.getAttribute("id"))//oImg oImg
//console.log(oImg.dataSrc,'+',oImg.getAttribute("data-src"))//undefined img/1.jpg IE里面前者为空
//oImg.gameid=900;
//console.log(oImg.gameid,oImg.getAttribute("gameid"));//自定义属性前者变,后者不变,IE678下面相同
//console.log(oImg.id,oImg.getAttribute("id"));//非自定义属性,更改两者相同
oImg.setAttribute("gameid","1000");
console.log(oImg.gameid,oImg.getAttribute("gameid"))//undefined 1000 IE 678 1000 1000
//总结 IE 678 两者始终相同 自定义属性和非自定义属性都相同,前者为number后者为string
//IE9+自定义属性两者都相同,非自定义属性两者无关,
</script>
</html>