javascript 将 div 放在固定位置的前面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30992940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:05:19  来源:igfitidea点击:

Bring div to front on fixed position

javascriptjqueryhtmlcss

提问by Kashish Arora

I used fixedpositionfor a divin a webpage to stick the divas a a header on the top, but on scrolling it comes behind all other objects like divs, videos and even text!

我用fixedposition了一个div在网页中贴div的顶部AA头,但滚动谈到像所有其他对象之后divs,视频,甚至发短信!

Here is the divas it should look at all times: div as it should look at all times

这是div它应该始终看到的样子: div,因为它应该一直看

How the divhides when it is scrolled down: div hides when it is scrolled down

div向下滚动时如何隐藏: div 向下滚动时隐藏

So, I just thought of the basic structure that if I write that particular div's code in the starting (which I did) and then other objects', the other objects will naturally come in front. So, one solution could be to write its code at the end. But, I have a structural code with proper placed comments in between and this could spoil it.

所以,我只是想到了基本结构,如果我div在开始时编写特定的代码(我这样做了),然后是其他对象,那么其他对象自然会排在前面。因此,一种解决方案可能是在最后编写其代码。但是,我有一个结构性代码,中间有适当的注释,这可能会破坏它。

This is the code:

这是代码:

<div style="width: 1409.25px; height:40px; top:0; left:0; position:fixed; background-color:black; line-height:2;">..Text here..</div>

Is there any way to bring the divin front when scrolling without writing its code at the end?

有没有办法div在滚动时将其置于前面而不在最后编写其代码?

回答by Matt Hammond

You need to add a z-index, this will put the divs into z space based on the z-indexvalue,

您需要添加一个z-index,这将根据z-index值将 div 放入 z 空间,

Example:

例子:

<div id="a" style="z-index:10"></div>
<div id="b" style="z-index:1"></div>

Div a will be placed above Div b as it has a higher z-index.

Div a 将放置在 Div b 上方,因为它具有更高的z-index.

Here is a simple JSFiddle example - https://jsfiddle.net/ta2gbn4m/

这是一个简单的 JSFiddle 示例 - https://jsfiddle.net/ta2gbn4m/

回答by Adarsh Gowda K R

For your header set the z-index value something higher then the below div wrapper

对于您的标题,将 z-index 值设置为高于下面的 div 包装器

example

例子

 header{
  position:fixed;
  width:100%;
  z-index:9999
}
div{
position:relative;
z-index:2 // lesser then the header z-index value
}

higher the z-index it comes on top of other element which had lower z-index value

z-index 越高,它位于 z-index 值较低的其他元素之上