gpt4 book ai didi

javascript - 更新测试样式时未更新 getComputedStyle

转载 作者:行者123 更新时间:2023-11-29 20:30:50 25 4
gpt4 key购买 nike

我想创建一个具有 display: none 的模拟 div 用于测试目的。但是,在测试中设置显示然后调用 getComputedStyle 显示样式没有变化,即

const parent = document.createElement('div');
const middle = document.createElement('div');

// If you check in the dom, the middle div clearly has display: none as
// part of its style
middle.style.display = 'none';
parent.appendChild(middle);

// Supposed to be 'none', but is actually ''
console.log(getComputedStyle(middle).display);

似乎其他人已经说过 getComputedStyle 强制重绘屏幕,但它似乎没有获得中间的更新显示。如何强制 getComputedStyle 更新显示值?

最佳答案

getComputedStyledisplay 属性返回空字符串,除非节点被添加到 DOM。您可以看到初始计算样式值也是空的,因为该节点未添加到 DOM。

如前所述in the spec ,在第 5 步,必须连接元素:

If elt is connected, part of the flat tree, and its shadow-including root has a browsing context which either doesn’t have a browsing context container, or whose browsing context container is being rendered, set decls to a list of all longhand properties that are supported CSS properties, in lexicographical order, with the value being the resolved value computed for obj using the style rules associated with doc.

const parent = document.createElement('div');
const middle = document.createElement('div');

console.log('Initial style: ', getComputedStyle(middle).display);
// If you check in the dom, the middle div clearly has display: none as
// part of its style
middle.style.display = 'none';
parent.appendChild(middle);

// Adding this, now it shows the correct value
document.body.appendChild(parent);

// Supposed to be 'none', but is actually ''
console.log('Display: ', getComputedStyle(middle).display);

关于javascript - 更新测试样式时未更新 getComputedStyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com