首页 > 解决方案 > 顺利追加内容到div

问题描述

我的网站在从菜单中选择后加载“子页面”并将其附加到一个空的隐藏 div。

它正在工作,但我对它的感觉并不满意。交换 div 的内容时,网站会出现口吃/闪烁。

所以,我正在做的是这样的:

HTML

<div class="button" id="page1">Button for link</div>
<div class="subContent">
    <div class="containerContentBox textLeft">                  
        <div id="placeContent"><!-- Content goes here --></div>                 
    </div>
</div>

在 Javascript 中,我试图通过淡出主 div 来平滑过渡,更改内容,然后将其淡入,如下所示:

JS

var chosenPage = "";

// Click button
$('.button').click(function(){              
    chosenPage = $(this).attr('id');    
    $('#placeContent').fadeOut('fast', function(){
        $('#placeContent').empty();
        showSelectedPage();
    });    
});

// Apply the page
function showSelectedPage(){        
    var newPageFile = "/pages/" + chosenPage + ".html";     
    $.get(newPageFile)
        .done(function(data) {          
            $('#placeContent').html(data);              
            $('#placeContent').fadeIn('fast', function(){
                scrollToContent();
            });
        }).fail(function() { 
            console.log('Page not found');
            return;
        });

}

// Scroll to top of the appended page   
function scrollToContent(){
    $('html,body').animate({
        scrollTop: $(".subContent").offset().top - 40
    }, 'slow');
}

有没有更好的方法来做到这一点?我认为闪烁/口吃来自滚动条改变高度。

标签: javascriptjquery

解决方案


推荐阅读