0

我的网页上有几张缩略图。当用户单击其中一个缩略图时,将打开全尺寸图片。对于浏览器窗口,全尺寸图片可能太大。为了使它适合,我有一个名为“setImageDimensions()”的 javascript 函数。此函数获取照片的宽度和高度,它们存储在页面上的“隐藏”输入字段中。问题是,当我单击缩略图时,会打开较大的图片,但未调整大小(如果它大于浏览器窗口)。我注意到(在“检查”HTML 时)heightwidth属性被添加到全尺寸图片(通过setImageDimensions()函数),但仅在一瞬间,之后这些值被删除。我的代码阻止这些属性“保留”的原因是什么?

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>
4

1 回答 1

4

在 上设置回叫。load()

$('div#photo_container'+photoID).load('get_photo.php', function(){
    setImageDimensions(photoID);
});
于 2012-07-15T02:32:43.717 回答