是新创建的元素,它不是DOM样式的一部分,或者所有值都设置为默认值

is newly created element, that is not part of the DOM styled or has all values set to default?

本文关键字:或者 默认值 设置 一部分 新创建 创建 DOM 元素 样式      更新时间:2023-09-26

首先创建元素:

var link = document.createElement('a');

我的文档被加载,样式和脚本生效。

样式可以是,例如:

a { background-color: salmon; }

所以它适用于所有的A标签。

在这些情况下,这个新创建的元素是否将所有CSS属性设置为规范中的默认值,并在插入DOM时进行样式设置,或者在创建时进行样式设置?

不,在元素被附加到DOM之前,它保持未样式化。或者,至少,它的计算样式是不可用的(大概是因为它还没有呈现):

HTML:

<a href="#">Something</a>
CSS:

a {
    color: purple;
}
JavaScript:

var body = document.getElementsByTagName('body')[0];
var a = document.createElement('a');
a.href = 'http://google.com/';
a.innerHTML = 'link to google';
console.log('color: ' + window.getComputedStyle(a,null).getPropertyValue('color'));
body.appendChild(a);
console.log('color: ' + window.getComputedStyle(a,null).getPropertyValue('color'));

JS小提琴。

如果,然而,你显式地用JavaScript样式元素,这增加了创建的元素的style属性,样式信息是立即可用的(尽管仍然不是通过getComputedStyle()):

var body = document.getElementsByTagName('body')[0];
var a = document.createElement('a');
a.href = 'http://google.com/';
a.innerHTML = 'link to google';
a.style.color = 'green';
console.log('color: ' + a.style.color);
body.appendChild(a);
console.log('color: ' + a.style.color);

JS小提琴。

插入文档时的样式:

 getComputedStyle( document.createElement('a') ).color;
//""
 getComputedStyle( document.body.appendChild( document.createElement('a') ) ).color;
//"rgb(0, 119, 204)"

对于好奇的人来说,这里有更多关于浏览器渲染如何工作的信息:http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/