如何使用.load和.fadeIn更改DIV内容?

3

我想要通过以下方式改变一个 Div 元素的内容:

$('#content').click(function() {
    $('#content').fadeOut().load('about.php').fadeIn('normal');
});

然而它总是闪烁,并且我不知道如何解决,因为我对jQuery有点缺乏经验。

我在这里看到了相同的问题,并尝试了所提供的答案,但都无济于事。

2个回答

4
你应该使用 .fadeOut().load() 函数的回调函数。目前你在同时进行淡出、添加 HTML 和淡入操作。 尝试:
//add event handler to click event for the #content element
$('#content').click(function() {

    //cache this element
    var $this = $(this);

    //fadeOut the element
    $this.fadeOut(function () {

        //after fadeOut is done, change it's HTML
        $this.load('about.php', function () {

            //now fadeIn the new HTML, this is in the callback for the `.load()`
            //function because `.load()` is an asynchronous function
            $this.fadeIn();
        });
    });
});


我将所有的callback函数嵌套起来,这样每个过程都可以在下一个运行之前完成。首先允许.fadeOut()完成,然后允许.load()获取数据并将其放置在DOM中,最后我们使用新HTML淡入元素。


3
你可以像这样做:

你可以这样做:

$('#content').click(function(){
  $('#content').fadeOut(function(){
     $('#content').load('about.php').fadeIn('normal');
  });
});

load 作为 fadeOutcallback 使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接