0
我的網頁上有幾張縮略圖圖片。當用戶點擊其中一個縮略圖時,就會打開全尺寸的圖片。瀏覽器窗口的全尺寸圖片可能太大。爲了使它適合我有一個名爲'setImageDimensions()'的JavaScript函數。此功能可以抓取照片的寬度和高度,並將其存儲在頁面的「隱藏」輸入字段中。問題是,當我點擊縮略圖圖片時,會打開更大的圖片,但它不會調整大小(如果它大於瀏覽器窗口)。我注意到(當「檢查」的HTML)該height
和width
屬性(通過setImageDimensions()
功能)加入到全尺寸的PIC,但僅一秒鐘,在此之後這些值被去除。我的代碼是什麼阻止這些屬性「保持」?如何設置ajaxed照片的寬度和高度?
的Javascript:
function viewImage(photoID) {
$('div#photo_container'+photoID).load('get_photo.php);
// the above will load something like <img src="path-to-full-size-pic" />
setImageDimensions(photoID);
}
function setImageDimensions(photoID) {
var width = $('#photoWrap'+photoID+ ' input#photoWidth').val();
var height = $('#photoWrap'+photoID+ ' input#photoHeight').val();
var windowWidth = $('body').width();
var windowHeight = $('body').height();
var newWidth = width; // initialize variable
var newHeight = height; // initialize variable
var ratio = 1; // intialize variable
if(width > windowWidth)
{
newWidth = windowWidth;
ratio = newWidth/width;
height = ratio * height;
width = newWidth;
if(height > windowHeight)
{
newHeight = windowHeight;
ratio = newHeight/height;
width = ratio * width;
height = newHeight;
}
$('div#photo_container'+photoID+' > img').attr('height', height);
$('div#photo_container'+photoID+' > img').attr('width', width);
}
else if(height > windowHeight)
{
newHeight = windowHeight;
ratio = newHeight/height;
width = ratio * width;
height = newHeight;
if(width > windowWidth)
{
newWidth = windowWidth;
ratio = newWidth/width;
height = ratio * height;
width = newWidth;
}
$('div#photo_container'+photoID+' > img').attr('height', height);
$('div#photo_container'+photoID+' > img').attr('width', width);
}
var halfWidth = width/2;
var halfHeight = (height/2);
$('#photo_container'+photoID).css('margin-left', -halfWidth);
$('#photo_container'+photoID).css('margin-top', -halfHeight);
}
HTML:
<div class="photoWrap" id="photoWrap3">
<input type="hidden" id="photoWidth" value="someWidth"/>
<input type="hidden" id="photoHeight" value="someHeight"/>
<div class="photo_container" id="photo_container3"></div>
<img id="previewPic3" src="path-to-thumbnail-pic" alt="" onclick="viewImage('3')" />
</div>
回調!對於!該!贏得! – Joshua 2012-07-15 02:33:59
就是這樣!非常感謝。我仍然是一個新手。 – 2012-07-15 04:45:29