将新图像内容加载到div后重新运行脚本

时间:2013-12-10 16:02:44

标签: jquery

我有根据屏幕大小调整图像大小的脚本。

图片脚本:

$(document).ready(function($){

        var ratios,
    adjustSize = function(){

    var total = 520, 
        win = $(window),
        winW = win.width(),
        winH = win.height()-150;

    $('#container img').each(function(i){
        var w = winH * ratios[i];
        $(this).css({
            height: winH,
            width : w   
        });
    total += w;
    });
    $('body').width(total);
};

    $(window).load(function(){
        ratios = $('#container img').map(function(){
            return $(this).width()/$(this).height();
        });
        adjustSize();   
    })
    .resize(function(){ adjustSize(); });
});

除非我尝试从外部文件将新内容加载到div中,否则一切都很有效,此调整大小的脚本不会再次重新运行并调整图片大小。

更改内容的脚本:

$(document).ready(function(){
           $("#id").click(function(){
            $('#container').load('some.html').hide().fadeIn('slow');
            });
         });

如何更改脚本? 我尝试了一个事件.click()但它不起作用或者我做错了。 我真的被卡住了,请有人帮忙!

由于

3 个答案:

答案 0 :(得分:2)

在load loadback中调用adjustSize()函数(隐藏它之前)

$('#container').load('some.html',function(){
     adjustSize();
     $(this).hide().fadeIn('slow');
});

答案 1 :(得分:1)

您正试图在其上下文之外访问“adjustResize()”函数。

尝试将其添加到文件的最顶层

var adjustSize;

然后添加“;”而不是“,”在“比率”中,所以它看起来像这样:

var ratios;
adjustSize = function(){

答案 2 :(得分:0)

您可以使用load的回调功能在完成后调用该功能:

$(document).ready(function(){
       // Click event is needed assuming that you want the load to happen only when the element with id 'id' is clicked
       $("#id").on('click', function(){
            $('#container').load('some.html', function () {
                // Do something after load (wrap your image resizing code in a function and call it here)
            })
            .hide().fadeIn('slow');
        });
     });