0

我正在使用 JQuery.load() 将文件的内容拉入网页。实现这一点的 javascript 位于一个单独的 .js 文件中,以保持整洁。

/* Pulls in file contents */
    $(function() {
    $('.div').load('file.html');
});

但是,当在我用来交叉淡入淡出图像的 jquery 动画中拉取文件时——其代码也在 .js 文件中——不起作用。

/* Crossfade code */
$(function(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
        $(this).fadeTo(200, 1);
    });
$(".appearing-image img").mouseout(function () {
        $(this).fadeTo(200, 0);
    });
});

我发现让它工作的唯一方法是将它包含在 .load() 代码中。

/* Pulls in file contents and executes animation */
$('.div').load('file.html',     $(function(){
            /* Crossfade images */
            $(".appearing-image img").css("opacity",0).fadeTo(300, 0);
            $(".appearing-image img").mouseover(function () {
            $(this).fadeTo(200, 1);
            });
            $(".appearing-image img").mouseout(function () {
            $(this).fadeTo(200, 0);
            });
        });
    });

这样可行。

但是,页面上的其他图像不会交叉淡入淡出,除非代码本身也包含在内,与 .load() 分开,这意味着我现在包含了两次代码。

有没有办法避免这种情况?

4

2 回答 2

2

使用外部函数,例如crossfade()

/* Crossfade code */
function crossfade(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
        $(this).fadeTo(200, 1);
    });
$(".appearing-image img").mouseout(function () {
        $(this).fadeTo(200, 0);
    });
}

/* Pulls in file contents and executes animation */
$('.div').load('file.html', function(){
    /* Crossfade images */
    crossfade();
});
于 2012-08-22T14:43:24.897 回答
0

您可以使用

$(window).bind('setup', function() {
   //code
});

在文档准备好之前加载一些东西

于 2012-08-22T14:44:46.107 回答