如何设置ajaxed照片的宽度和高度?

时间:2012-07-15 02:30:00

标签: jquery ajax image

我的网页上有几个缩略图。当用户点击其中一个缩略图时,将打开全尺寸图片。对于浏览器窗口,全尺寸pic可能太大。为了使它适合我有一个名为'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>

1 个答案:

答案 0 :(得分:4)

在。load()

上设置回电
$('div#photo_container'+photoID).load('get_photo.php', function(){
    setImageDimensions(photoID);
});