我對Jquery很新,我遇到以下問題。在Jquery中調整圖像大小保持加載
我寫了一個函數來調整圖像的大小,同時保持寬高比。我有更多的「如果」比這個版本需要更多的可讀性。 html結構就是這樣的。
<div class="post">
<div class="date"></div>
<div class="thumbnail">
<img class="img-thumb" />
</div>
<div class="post-body">
<p>...</p>
<img />
<p>...</p>
</div>
</div>
尺寸調整(我也加入一些填充中心的形象。我覺得我沒有錯的那部分代碼。)
$(window).load(function() {
var parentWidth = 250;//max width. In the real script i get the parent width inside the each but for the example a static value is ok
var parentHeight = 196;//max height
$('.img-thumb').each(function() {
var img=$(this);
var width = img.width(); //image width
var height = img.height(); //image height
var aspect = width/height;
var wide = width/parentWidth;
var tall = height/parentHeight;
if(width > parentWidth) {
if (wide > tall) {
width = parseInt(parentWidth,10);
height = parseInt(parentHeight/aspect,10);
}
}
if(height > parentHeight) {
if (tall > wide) {
height = parseInt(parentHeight,10);
width = parseInt(parentWidth*aspect,10);
}
}
margin_top = parseInt((parentHeight - height)/2,10);
margin_left = parseInt((parentWidth - width)/2,10);
img.css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :height + 'px',
'width' :width + 'px'
});
});
});
這裏是我的問題。我不明白負載是如何工作的。我的意思是。這將工作,但只有當所有的圖像加載。但它有兩個問題。第一個是它必須等待所有的加載,第二個是用戶將看到調整大小,所以我首先必須隱藏圖像並用show()顯示它們。我可以在CSS中做到這一點,但當JavaScript被禁用,他們仍然會被隱藏,所以我更喜歡在jQuery中做到這一點。
我可以運行第二個。每個之前,並隱藏它們,但我想第二次運行一個同樣的事情不是最好的解決方案。那麼負載如何工作?
如果我這樣做,例如:
$('.img-thumb').each(function() {
var parentWidth = 250;//max width. In the real script i get the parent width inside the each but for the example a static value is ok
var parentHeight = 196;//max height
var img=$(this);
img.hide();
img.load(function() {
var width = img.width(); //image width
var height = img.height(); //image height
var aspect = width/height;
var wide = width/parentWidth;
var tall = height/parentHeight;
if(width > parentWidth) {
if (wide > tall) {
width = parseInt(parentWidth,10);
height = parseInt(parentHeight/aspect,10);
}
}
if(height > parentHeight) {
if (tall > wide) {
height = parseInt(parentHeight,10);
width = parseInt(parentWidth*aspect,10);
}
}
margin_top = parseInt((parentHeight - height)/2,10);
margin_left = parseInt((parentWidth - width)/2,10);
img.css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :height + 'px',
'width' :width + 'px'
}).show();
});
});
它不工作。我的意思是我仍然可以看到調整大小。我想原因是每個循環的第二部分在第一個圖像加載之前不會執行。那麼我如何告訴jquery執行加載代碼的outdise?我需要兩個。每個?
你的解釋中有一點含糊不清,你說「... jQuery,它應該等到頁面完成加載.....」應該完成加載DOM元素,而不是任何真正的媒體。 –
感謝您的回覆。 1)我可以使用css來隱藏它們,但如果用戶禁用javascript,它們將保持隱藏狀態。2)我知道最好的方法是將圖像的縮略圖存儲起來。基本上每次上傳圖片時,php都可以自動創建縮略圖。但這不是我想要的,因爲我正在創建一個主題。所以我不知道用戶會做什麼/上傳:)。 –
請查看我上面關於CSS關注的編輯。希望能幫助到你 – Sthe