jQuery 中有没有办法将 div 放在前面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3233219/
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
Is there a way in jQuery to bring a div to front?
提问by anthonypliu
If I had a bunch of absolute positioned divs and they overlapped, how would I get a certain div to come to the front? Thanks again guys!
如果我有一堆绝对定位的 div 并且它们重叠,我如何让某个 div 出现在前面?再次感谢各位!
回答by Kerry Jones
This is a CSS thing, not a jQuery thing (though you can use jQuery to modify the css).
这是 CSS 的东西,而不是 jQuery 的东西(尽管您可以使用 jQuery 来修改 css)。
$('element').css('z-index', 9999); // note: it appears 'zIndex' no longer works
Or, absolute positioning will bring something to the top:
或者,绝对定位会带来一些东西:
$('element').css('position', 'absolute');
回答by Yarin
With jQuery(like you asked):
使用 jQuery(就像你问的那样):
$('#a-div').parent().append($('#a-div')); // Pop a div to the front
Weird how everyone went with z-index. Why override natural stacking order when you can just pop it to the front within the DOM?
奇怪的是每个人都如何使用 z-index。当您可以在 DOM 中将其弹出到最前面时,为什么要覆盖自然堆叠顺序?
回答by forresto
When you are working with multiple elements you'll have to loop through and see which has the highest z-index, and set the top to that+1.
当您处理多个元素时,您必须循环查看哪个具有最高的 z-index,并将顶部设置为那个 +1。
http://jsfiddle.net/forresto/Txh7R/
http://jsfiddle.net/forresto/Txh7R/
var topZ = 0;
$('.class-to-check').each(function(){
var thisZ = parseInt($(this).css('zIndex'), 10);
if (thisZ > topZ){
topZ = thisZ;
}
});
$('.clicked-element').css('zIndex', topZ+1);
For a non-CSS version (if none of the layers have z-index specified) you can also just append the element again:
对于非 CSS 版本(如果没有指定图层的 z-index),您也可以再次附加元素:
$('.click-to-top').click(function(){
$(this).parent().append(this);
});
(I don't know if that is slower than with CSS z-index
.)
(我不知道这是否比 CSS 慢z-index
。)
For non-CSS non-jQuery, just append it again:
对于非 CSS 非 jQuery,只需再次追加:
// var element = document...;
element.parentNode.appendChild(element);
回答by user12915978
element.style.zIndex = Date.now();
回答by airmanx86
Use .css() and apply position attribute and z-index attribute.
使用 .css() 并应用位置属性和 z-index 属性。
回答by Gert Grenander
It would be overkill to use jQuery for this. Instead use CSS' z-index property:
为此使用 jQuery 将是矫枉过正。而是使用 CSS 的z-index 属性:
<style type="text/css">
#myElement {
z-index: 50000;
}
</style>