2017-02-11 77 views
0

在我正在处理的网页上,我有一行和两个单元格的简单html表格。这些占据了整个页面何时/如何将CSS样式应用于动态添加的元素?

<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有冲突。

+1

我想尝试'位置:上'SVG-cell' relative'以及添加'顶部:0;正确:0;底部:0;左:0; z-index:1;'从'#block-svg'中删除'height'和'width'/ – maddockst

回答

1

我无法重现您的问题。不过,我认为你可以用一个伪元素来完成同样的覆盖技术,并且你的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>

+0

这工作谢谢!但是我仍然不确定为什么我做的没有工作 – Ben

相关问题