[英]Using jQuery UI .position on img with width: auto
我正在建立一个非常简单的画廊。 单击缩略图时,应在窗口中央固定弹出一幅完整的图像,并带有周围的div以使其变为模态。
我正在努力使jQuery的.position方法起作用。 如果我设置图像的像素高度和宽度,则效果很好。 但是,如果我设置像素的高度和宽度:自动,则图像不会居中对齐。 我认为在这种情况下,居中是基于零宽度完成的。
$(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行注释掉,以了解我的意思。
我有点重做了一些代码,在此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();
});
});
另外,请查看Smashing Magazine上有关完美水平和垂直位置的文章。
我尚未回答您的问题,但是出于好奇,为什么不使用那里非常有用的灯箱画廊之一?
1. http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
2. http://fancyapps.com/fancybox/
我不知道这是否是一个导致宽度失败的错误:“自动”,但是我找到了一种方法,可以通过预先计算纵横比来计算像素宽度。
//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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.