0

最近我尝试在灯箱中制作图像。如果您单击图像,它会以灯箱效果显示。但其中一些原因是,Lightbox 没有在窗口大小中正确居中。例如,如果您单击它在灯箱中加载的图像,但它第一次在站点底部加载灯箱,然后再次单击它正确对齐的图像。这是我所说的截图。页面加载时单击图像时的第一个屏幕截图。

第一次点击图片

第一张图片

第二次点击图片

第二次之后 第一次遇到对齐问题。第二次没有对齐问题(没有页面加载) Javascript:

 <script>
                jQuery(document).ready(function() {
                    jQuery("img").click(function() {
                          var img_path;               
            if ($(this).parent('a').length) {

                           img_path = $(this).parent('a').prop('href');
                            }
                        else
                            {
                         img_path = $(this).attr('src');
                            }

                        jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
                        jQuery(".cpoutter").css('display', 'block');
                        jQuery('.cpoutter').animate({'opacity': '1'});
                        //jQuery('.lightbox').animate({'opacity':'1.00'});
                        var cplightbox = document.getElementsByClassName('cplightbox')[0];
                        var cpoutter = document.getElementsByClassName('cpoutter')[0];
                        cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
                        return false;
                    });
    });
    </script>

HTML 代码:

这是小提琴 http://jsfiddle.net/rCUGD/7/

但是这个脚本如何在 jsfiddle.net 中正常工作。可能是我搞砸了脚本或 css

我不在我犯错的地方

编辑:

现在@JustAnil之后是截图: 在此处输入图像描述

第二次点击后它应该像这样正常显示

在此处输入图像描述

4

1 回答 1

1

签出这个工作的 JSFiddle

您需要更改以下几行(计算偏移量的位置)。

更改以下行:

 var cplightbox = document.getElementsByClassName('cplightbox')[0];
 var cpoutter = document.getElementsByClassName('cpoutter')[0];
 cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";

var cplightbox = document.getElementsByClassName('cplightbox')[0];

// We need the actual height of the image so grab it from the "inner" container
var cplightbox1 = document.getElementsByClassName('cplightbox1')[0]; // New Line

var cpoutter = document.getElementsByClassName('cpoutter')[0];

// Calculate the (negative) offset from the width & height
cplightbox.style.marginLeft = "-"+$(cplightbox1).width() / 2 + "px";
cplightbox.style.marginTop = "-"+$(cplightbox1).height() / 2 + "px";
// ^ Negative offset so we can vertically and horizontally center it.

最后

将您的 CSS 从以下位置更改:

.cplightbox {
    margin-left: auto;
    margin-right:auto;
    width:auto;
    height:auto;
    display:inline-block;
}

至:

.cplightbox {
     position:fixed;
     top:50%;
     left:50%;
     display:inline-block;
 }

签出这个问题CSS Vertically & Horizo​​ntally Center Div(这就是如何将 div 居中到屏幕中间)。

然后更改您的 javascript 以计算偏移量(取决于图片的大小[即宽度和高度的 50%])

查看这个工作的 JSFiddle

于 2013-07-10T10:37:49.067 回答