2011-12-24 126 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({ 
     //... 
    }); 
    //... 
}); 

然後將圖像尺寸,從而對話框的大小會時顯示對話框,該對話框可以正確定位自己知道。