2013-08-26 14 views
1

我有一個圖像調整到屏幕大小,但.height.width()不調整,使我的margin-leftmargin-top改變。有沒有辦法讓它調整?.height().width()不會調整大小的變化

var $src = $(this).attr("href"); 
    $('#overlay').append('<img class="image" src="' + $src + '" />'); 
    var $image = $('img'); 
    $('.image').css('max-height','80%'); 
    $('.image').css('max-width','90%'); 
    $('.image').css('position', 'fixed'); 
    $('.image').css('top', '50%'); 
    $('.image').css('left', '50%'); 
    var $height = $image.height(); 
    var $width = $image.width(); 
    $('.image').css('margin-top', (($height/2)*-1)); 
    $('.image').css('margin-left', (($width/2)*-1)); 

http://jsfiddle.net/a8a4Y/

+0

他們將始終爲0,因爲你有兩個圖像(圖像$沒有源)。此外,該信息僅在圖像加載後纔可用。 – Matthias

+0

正如你已經固定嘗試應用保證金:0自動而不是左上角50%技術。 –

回答

1

問題在於,當您使用圖像時,圖像未加載。所以高度,寬度將始終爲零。

http://jsfiddle.net/W8sNw/

所以你可以做的是增加一個處理程序load event,當被解僱,你可以執行代碼:

var $src = $(this).attr("href"); 
$('#overlay').append('<img class="image" src="' + $src + '" />'); 
var $image = $('img'); 
$image.on("load",function(){ // This is the new stuff, it listen to the load event 
          // which is fired when the image is loaded and the size 
          // size is known 

    var $height = $image.height(); 
    var $width = $image.width(); 
    $('.image').css('margin-top', (($height/2)*-1)); 
    $('.image').css('margin-left', (($width/2)*-1)); 
    console.log("Height: " + $height); 
    console.log("Width: " + $width); 
}) 

我還包括一個例子更優化的代碼。例如,每次使用選擇器時,JavaScript都會在DOM中搜索該元素。您應該只此一次,看看: http://jsfiddle.net/W8sNw/2/

+0

你應該把所有的css道具合併成一個函數。 – Jashwant

+0

@Jashwant我更新了第二個例子。我希望第一個人重申OPs語法。 –

0

試試這個:

var $src = $(this).attr("href"); 
    $('#overlay').append('<img class="image" src="' + $src + '" />'); 
    var $image = $('img') 
$image.ready(function(){ 

    $('.image').css('max-height','80%'); 
    $('.image').css('max-width','90%'); 
    $('.image').css('position', 'fixed'); 
    $('.image').css('top', '50%'); 
    $('.image').css('left', '50%'); 
    var $height = $image.height(); 
    var $width = $image.width(); 
    $('.image').css('margin-top', (($height/2)*-1)); 
    $('.image').css('margin-left', (($width/2)*-1)); 
}); 
相關問題