我正在建立一个非常简单的画廊。单击缩略图图像时,应在窗口中央弹出一个全尺寸图像,并使用周围的div使其成为模态。
我正在努力使jQuery的.position方法工作。如果我为图像设置像素高度和宽度,它可以正常工作。但是,如果我设置像素高度和宽度:auto,则图像不会居中。我认为在这种情况下居中是基于零宽度完成的。
$(document).on("click", ".galleri", function() {
if ($("#imgFullWindow").length === 0){
$("body").append("<div id='imgFullWindow'></div>");
}
$("#imgFullWindow").css({
display : "none",
position : "absolute",
"z-index": "5",
top : "0px",
left : "0px",
width : $(document).width(),
height : $(document).height(),
background: "rgba(0,0,0,0.7)"
}).append("<img />");
$("#imgFullWindow img").attr("src", $(this)[0].src).css({
height : "150px",
width : "120px", //This works
//width : "auto", //This doesn't
position : "fixed"
}).position({
my: "center",
at: "center center+40",
of:$(window),
collision: "none"
});
$("#imgFullWindow").fadeIn(500);
});
请看我的小提琴:http://jsfiddle.net/apAu3/尝试评论第19行并取消注释第20行,看看我的意思。
答案 0 :(得分:1)
我有点重新编写代码,在jfiddle处(你必须满足你的需求):
HTML:
<div>I'm the image container. Click the image!
<img class='galleri' src='http://upload.wikimedia.org/wikipedia/en/2/27/LightningMcQueen.jpg' />
</div>
CSS:
.galleri {
border: 1px solid red;
height: 50px;
width : "auto";
}
.big-image {
/*perfect horizontal and vertical positioning*/
position: absolute;
left: 0; top: 0; right: 0; bottom: 0;
/*in order for this perfect positioning to work,
the element needs a declared width OR height,
along with margin: auto*/
margin: auto;
height: 150px;
}
div {
border: 1px solid blue;
}
.box {
width: 100%; height: 100%;
background: rgba(0,0,0,.7);
position: absolute;
left: 0; top: 0;
display: none;
}
jQuery的:
$('img.galleri').on('click',function() {
var box = $('.box') || null;
if($('.box').length < 1) {
var bigImage = $(this).clone();
$('body').append('<div class="box"></div>');
$('.box').fadeIn().append(bigImage);
bigImage.addClass('big-image');
}
});
$('body').on('click','.box',function() {
$(this).fadeOut(function() {
$(this).remove();
});
});
另外,请查看this Smashing Magazine article关于完美水平和垂直定位的信息。
答案 1 :(得分:0)
我还没有回答你的问题,但出于好奇,为什么不使用其中一个非常有用的灯箱画廊呢?
1. http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
2. http://fancyapps.com/fancybox/
答案 2 :(得分:0)
我不知道这是一个错误导致定位失败的宽度:“auto”,但我找到了一种方法,通过提前计算宽高比来计算像素宽度。
//Find the image aspect ratio
var imgRatio = ($(this).height()/$(this).width())
然后在.css方法中:
height : $(window).height(),
width : ($(window).height() / imgRatio), //This works
新jsfiddle:http://jsfiddle.net/K3ubS/