attribute&property

attribute:

对html标签来说就是它的句柄(节点属性)
html预定义属性:比如 input标签的 type、name、value、class 这些html自带的。
html自定义属性:随意怎么定义 xxx=’xxx’。

property:

js原生dom对象的直接属性
image.png
每一个预定义的attribute都会有一个property与之对应在js的dom对象上,而自定义的属性只在dom对象中的attributes中找的到。
attributes是个伪数组。

那么问题来了,当我们使用js更改一个元素对象的直接属性(property),又更改了元素对象上的attributes(节点属性)且值不一样会怎么样哪?

这里又牵扯一个 property 布尔值类型和非布尔值类型的问题

property有布尔值类型和非布尔值类型:
非布尔值类型:如name
这样的非布尔值类型,不管什么情况下property和attribute都会同步。

  1. 布尔值类型:如checkbox checked属性实际上它判断的只是 true false。<br /> **目前就自己的观察发现是不会同步**,先不下绝对定论。

经过实验对于浏览器和用户操作

使用js操作 checkbox 的直接属性(property).checked 和 attributes 时发现浏览器和用户操作相对比较同步的是property,只有当property没有明确设置的适合,才会已attributes的为准。
用户操作是property,浏览器认准的也是proerty

总结

1. 什么是attribute,什么是property

html标签预定义和自定义的属性,我们统一称为attribute。
js元素dom对象的直接属性,我们统称位property。

2.什么是布尔属性,什么是非布尔值属性

property的属性值位布尔类型的,我们统称为布尔值属性。
property的属性值为非布尔值类型的,我们统称为非布尔值属性。

3.attribute和property的同步关系

非布尔值属性:实时同步。
布尔值属性:
property不会同步attribute。
在没设置过property的情况下:attribute会同步property。
在设置过property的情况下:attribute不会同步property。

4.用户操作的是property

5.浏览器认准的是property

这就会在使用js操作dom的时候可能出现bug,比如使用jquery操作dom使用:$(‘checkbox’).attr(‘checked’,true); 操作的是attribute,就是说如果用户手动设置过property,那么这段代码就达不到想要的效果了,应为attribute不能同步已经设置过值的property。

let headerBox = document.getElementById(“header-box”);
let allItem = document.getElementsByClassName(“el”);
let arrEl1 = […allItem];
let arrStyle = [];

let buttons = document.getElementsByTagName(“button”);
buttons[0].onclick = function () {

**_arrStyle _**= [];<br />    **_arrEl1 _**= [...**_allItem_**];<br />    for (let i1 = 0; i1 < **_arrEl1_**.length; i1++) {<br />        **_arrStyle_**.push(`transform:${**_arrEl1_**[i1].style.transform};left:${**_arrEl1_**[i1].style.left};top:${**_arrEl1_**[i1].style.top};`)<br />    }

for (let i = 0; i < **_arrEl1_**.length - 1; i++) {<br />        **_arrEl1_**[i + 1].style = **_arrStyle_**[i];<br />    }

**_headerBox_**.append(**_allItem_**[0]);<br />    **_arrEl1_**[0].style = **_arrStyle_**[**_arrStyle_**.length - 1];

**_allItem _**= **_document_**.getElementsByClassName("el");

}
buttons[1].onclick = function () {

}