2011-12-24 132 views
1

有人会向我解释为什么我的对话框只有部分时间中心吗?有时第一次对话框将图片加载到右侧,但如果再次单击该图片,它会居中。有时图像将居中,我刷新页面,它的中心偏离?jquery对话框定位

我有以下的标记......

<div class="details"> 
<img id="photo1" class="photos opacity" src="images/photos/angledBuilding_sm.jpg" alt="photography" /> 
</div> 

和下面的.js ...

$('.photos').click(function() { 
var id = this.id; 
var src = this.src; 
var lrg = "_lg"; 
var sm = "_sm" 
var title = 'This title';//create a separate function to set the title of the image. 
var srcNew = src.replace(sm, lrg); 
var $dialogImg = '<div><img src=' + srcNew + ' /></div>' 
var $dialog = $($dialogImg) 

.html($dialogImg) 
.dialog({ 
autoOpen: true, 
modal: true, 
title: ' ' + title + ' ', 
width: 'auto', 
height: 'auto', 
resizable: false, 
draggable: false, 
}); 

$dialog.dialog('open'); 
$(id).dialog('option', 'position', 'top center'); 
}); 

您可以在http://jameswadeweaver.com/portfolio.php

看到这个底部的摄影节的页面是我遇到中心问题的地方。

回答

2

这不是一个居中问题。这是一个大小问题。您的对话框是在图像加载之前创建的,所以它使用了一些基本的尺寸框,它是居中的。但是,图像完成加载并溢出对话框容器。

我会建议添加加载事件处理程序到img标记移动你的.dialog(...)代码。沿着这些线

$('.photos').click(function() 
{ 
    $("<img/>") 
     .on("load", function() { $("<div/>").append(this).dialog(...); }) 
     .prop("src", $(this).prop("src").replace("_sm", "_lg")); 
}); 

另外,你可以预先加载到窗口加载一个隐藏的div大图像,那么你不会有这个延迟。

+0

或者只是在''上只包含'width'和'height'属性...... – 2011-12-24 05:56:06

+0

这将是我的第一个建议,但是看到OP如何将他的对话框代码附加到许多不同的图像上,这可能是不同的尺寸,这可能不是一种选择。 – 2011-12-24 06:00:58

+0

但是,如果最初的''将它们作为数据属性,那么您可以获取对话版本的'width'和'height'。这就是我至少要做的事情,但负载处理程序是懒惰的合理解决方案:)或者无法访问服务器代码的人。 – 2011-12-24 06:07:16

0

liho1eye已经涵盖了您的问题的来源,并提供了一个合理的解决方案,但还有另一种可能性。

如果你知道大,小图像的尺寸,那么你可以改变HTML看起来像这样:

<img id="photo1" 
    class="photos opacity" 
    src="images/photos/angledBuilding_sm.jpg" 
    alt="photography" 
    width="281" 
    height="161" 
    data-lg-width="1123" 
    data-lg-height="642" /> 

的尺寸,当然,只是在这里做了编号。然后,你可以读出的数据属性来显示它之前适当大小的对话框:

$('.photos').click(function() { 
    var $this = $(this); 
    var id  = this.id; 
    var src = this.src; 
    var width = $this.data('lg-width'); 
    var height = $this.data('lg-height'); 

    //... 

    var $dialog = $('<div>').append(
     $('<img>', { 
      src: srcNew, 
      width: width, 
      height: height 
     }) 
    ); 
    $dialog.dialog({ 
     //... 
    }); 
    //... 
}); 

然后将图像尺寸,从而对话框的大小会时显示对话框,该对话框可以正确定位自己知道。