gpt4 book ai didi

javascript - css 样式何时/如何应用于动态添加的元素?

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:22 25 4
gpt4 key购买 nike

在我正在处理的网页上,我有一个简单的 html 表格,其中包含一行和两个单元格。这些占据了整个页面

<table>
<tr>
<td id="svg-cell">
<div id="svg-container">
<!-- the svg is going to go in here -->
</div>
<!-- a hidden
<div id="block-svg"><div>
will be inserted here in the JS code to prevent further user interaction
on the svg until the user does something else on the page
-->
</td>
<td>
<!-- some other not relevant stuff goes in here-->
</td>
</tr>
</table>

左边的单元格中会有一个 SVG,当用户点击 SVG 时,我想用透明的灰色覆盖层覆盖整个单元格,并阻止与该 SVG 的任何交互,直到他们在正确的单元格。使用以下 javascript:

let blockSVG = document.createElement('div')
blockSVG.id = "block-svg"
blockSVG.innerHTML = "Please select an item on the right"

document.getElementById("svg-cell").appendChild(blockSVG)

然后我有这个对应的 css:

div#block-svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
text-align: center;
}

现在,除了有时 SVG 非常大之外,所有这些都按预期工作得很好。它可以占用比页面上更多的空间,当这种情况发生时,即使我可以在浏览器控制台中看到我的 div 已正确添加到页面并且确实有“block-svg”作为其 ID .. CSS用灰色覆盖覆盖 div 似乎没有生效。如果我然后在页面上滚动,CSS 就会生效。我最好的猜测是浏览器以某种方式确定我的 div#block-svg 不可见,因此它不会计算/应用 css。

如有任何建议,我们将不胜感激。

作为旁注,这个 css 绝对不可能与其他一些 css 发生冲突。

最佳答案

我无法重现您的问题。但是,我认为您可以使用伪元素执行相同的覆盖技术,并且您的 JS 可以添加/删除启用或禁用覆盖的类。

document.getElementById('svg-cell').classList.add('overlay');
#svg-cell {
position: relative;
}
.overlay:after {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
text-align: center;
content: 'Please select an item on the right';
}
<table>
<tr>
<td id="svg-cell">
<div id="svg-container">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</div>
</td>
</tr>
</table>

关于javascript - css 样式何时/如何应用于动态添加的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171496/

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