javascript:确保元素始终出现在顶部 [英] javascript: ensure element always appears on top
问题描述
我创建了一个简单的 chrome 扩展工具,用于在用户将浏览的页面上显示小文本消息(z-index 为 999999 的 div).有时,div 仍然出现在现有页面的元素下方,更糟糕的是,div 的内容会发生变化,因为页面已经有了自己的 CSS 规则.
I created a simple chrome extension tool to show small text message (a div with z-index 999999) on the page a user will be browsing. Sometimes, the div still appears below the existing page's elements and worse, the contents of the div changes because the page already has it's own CSS rules.
挑战在于如何确保我的文本消息显示在所有元素的顶部(适用于任何网站),并且看起来一致且不受现有 CSS 规则的影响.
The challenge is how to ensure that my text message will appear on top of all elements (works on any site) and that it will look consistent and unaffected by existing CSS rules.
iframe 能解决这个问题吗?但是,即使使用 iframe,它仍然需要出现在所有元素之上,而且 z-index 似乎并不总是有效.
Would iframe solve this issue? But still, even with an iframe, it still needs to appear on top of all elements and seems like z-index doesn't work always.
推荐答案
如果您想与任何元素重叠任何内容,请使用 z-index
.您必须考虑:
If you want to overlap anything with any element, use z-index
. You must consider:
您必须使用最高的
z-index
值,以便将元素置于同一 堆叠上下文.
请参阅Z-INDEX 的最小值和最大值.
You must use the highest
z-index
value you can, in order to position the element above other elements in the same stacking context.
See Minimum and Maximum value of Z-INDEX.
要使 z-index
工作,元素必须被定位.
例如,position:relative
或 position: absolute
.
To make z-index
work, the element must be positioned.
For example, position: relative
or position: absolute
.
一个巨大的 z-index
如果它的堆叠上下文低于其他元素,那么它就毫无用处.为了避免这种情况:
A huge z-index
will be useless if its stacking context is below other elements.
To avoid this situation:
- 尽可能减少元素的祖先数量,这可能会堆叠上下文.
- 确保它们没有堆叠上下文.他们将需要
z-index:自动
不透明度:1
- 在某些浏览器上,
position
不应fixed
will-change
不应是上述任何属性
- Reduce as much as you can the number of ancestors of your element, which potentially could be stacking contexts.
- Make sure they aren't stacking contexts. They will need
z-index: auto
opacity: 1
- On some browsers,
position
shouldn't befixed
will-change
shouldn't be any of the properties above
如果有 flash,你将无法与
z-index
重叠,除非你将它的wmode
属性修改为transparent
或不透明
.
请注意,此更改会损害该小程序的性能.If there is flash, you won't be able to overlap it whatever the
z-index
unless you modify itswmode
attribute totransparent
oropaque
.
Note this change will hurt the performance of that applet.或者,HTML5 引入了
元素,它有
showModal
方法.Thad 方法在调用时将对话框推送到文档的 待处理对话框堆栈,这意味着它将被添加到顶层 层.Alternatively, HTML5 introduces
<dialog>
element, which hasshowModal
method. Thad method, when called, pushes the dialog to document's pending dialog stack, which means that it will be added to the top layer layer.这篇关于javascript:确保元素始终出现在顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!