gpt4 book ai didi

javascript - 为什么StyleSheet 的ownerNode 插入后为null?

转载 作者:行者123 更新时间:2023-11-29 23:16:18 25 4
gpt4 key购买 nike

有人可以解释为什么在我将其 textContent 设置为某项后,StyleSheetownerNodenull 吗?

const style = document.createElement('style')
document.head.appendChild(style)
const sheet = style.sheet
// passes
console.assert(sheet.ownerNode !== null, 'ownerNode is null')
sheet.ownerNode.textContent = 'div { color: red }'
// fails
console.assert(sheet.ownerNode !== null, 'ownerNode is null')

最佳答案

因为通过完全替换节点的文本,您创建了一个新的替换样式表对象:

const style = document.createElement('style')
document.head.appendChild(style)
const sheet = style.sheet
sheet.ownerNode.textContent = 'div { color: red }'
console.log(style.sheet === sheet); // <===== false!
console.log(style.sheet.ownerNode === style); // <===== true

旧节点不再存在于 DOM 中,因此它没有 ownerNode

关于javascript - 为什么StyleSheet 的ownerNode 插入后为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682047/

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