无法居中图像

时间:2012-06-20 22:17:11

标签: javascript jquery css

我试图将屏幕变黑并将图像置于屏幕中间,高于所有其他元素。我所拥有的不起作用(图像居中部分)。

注意 - 我知道可能有这个插件..但我正在试图弄清楚如何操作以及它是如何工作的。

var docHeight = $(document).height();

$("body").append("<div id='overlay'></div>");

$("#overlay").height(docHeight).css({
    'opacity': 0.4,
    'position': 'relative',
    'top': 0,
    'left': 0,
    'color': 'white',
    'background-color': 'black',
    'width': '100%',
    'z-index': 5000
});

$("#overlay").append("<div id='image-container'><img id='photo' src='" + $(this).attr('rel') + "' alt='image' /></div>");

$("#image-container").css("position", "absolute");
$("#image-container").css("top", Math.max(0, (($(window).height() - $("#image-container").outerHeight()) / 2) + $(window).scrollTop()) + "px");
$("#image-container").css("left", Math.max(0, (($(window).width() - $("#image-container").outerWidth()) / 2) + $(window).scrollLeft()) + "px");

CSS:

#image-container {
    background: #FF0000;
    z-index: 999999;
}

我正在显示的图像位于屏幕的右下角...不在中央。我做错了什么?

JsFiddle Here

3 个答案:

答案 0 :(得分:1)

Centering elements vertically is hard。一个简单的解决方法是围绕屏幕元素的背景:

#overlay {
    /*Cover the entire screen regardless of scrolling*/
    position:fixed;top:0;right:0;bottom:0;left:0;
    background: #ff0000 url(...) no-repeat 50% 50%;
}
带有半透明bgcolor的

Fiddle'd用于演示目的

答案 1 :(得分:0)

你可以使叠加层固定,宽度和高度分别为100%和大zindex。现在你有一个半透明的黑色div覆盖整个窗口,而不是你正在尝试的整个文档。因为我们已定位固定它即使滚动页面也不会滚动。现在以图像为中心使用简单的数学运算。一种方法是将图像定位为绝对值,左边为50%,然后marginleft为 - (图像宽度/ 2)。如果图像宽度对于所有情况都相同并且可以在css上添加,则这很有用。在这种情况下,你只需要用jquery淡化和淡出overlay div。现在没有代码,因为我在移动设备上。

答案 2 :(得分:0)

您可以使用纯CSS执行此操作:http://jsfiddle.net/5rRqS/2/(我不确定所有浏览器)。

当你的脚本运行时,图像有宽度= 0px和高度= 0所以,如果你想使用JS,你必须在加载图像后运行定位脚本,或者添加图像宽度和高度(按属性或样式)< / p>

然后使用类似

的内容
$(img).load(function(){
   // positioning script here
})