使用jQuery .load()获取元素高度的问题

Issue getting height of element when using jQuery .load()

本文关键字:元素 高度 问题 获取 jQuery load 使用      更新时间:2023-09-26

我的脚本有一个问题,通过jQuery .load()加载内容到页面。内容正确加载,我的动画说的内容工作(完成类"隐藏"),但我在加载之前设置包装容器的高度,然后动画说的容器的高度,以保持页面之间的不同内容的高度跳。

实际上发生的是,由于某种原因,高度被设置为0,而不是元素的实际高度。奇怪的是,这似乎在最初的点击中起作用,但在任何其他情况下,它会中断并将高度设置为0。

请参阅下面的代码(我将创建一个jsFiddle,但.load()不起作用):

<main id="content" class="content">
    <div id="content-inner" class="content-inner">
        <!-- Content -->
    </div>
</main>
CSS

.content {
    transition: .25s height;
}
.content-inner {
    position: relative;
    top: 0;
    opacity: 1;
    visibility: visible;
    transition: .25s opacity, .25s top;
}
.hidden .content-inner {
    top: -30px;
    opacity: 0;
    visibility: hidden;
    transition: .25s opacity, .25s top, 0s visibility .25s;
}

JavaScript (jQuery)

var $mainContentOuter = $('#content'),
    linkContent = '#content-inner',
    $mainContentInner = $(linkContent);

function loadMainContent(link) {
    // Assign height as current height to prevent jumping
    $mainContentOuter.height( $mainContentInner.outerHeight() );
    // Hide content
    $mainContentOuter.addClass('hidden').delay(250).queue(function() { 
        // Load content
        $mainContentOuter.load(link + ' ' + linkContent, function() {
            // Animate the height difference when loaded
            $mainContentOuter.height($mainContentInner.outerHeight());
        });
        // Dequeue for delay
        $(this).dequeue();
    }).delay(250).queue(function() {
        // Reveal content and reset height
        $mainContentOuter.removeClass('hidden').css('height','');
        // Dequeue for delay
        $(this).dequeue();
    });
}
// Override behavior of navigational links
$('.nav-main > li > a').click(function(e){
    var link = $(this).attr('href');
    //Pass link
    loadMainContent(link);
    e.preventDefault();
});

任何帮助都将是非常感激的。

提前感谢,Rob

问题是您将内部内容加载到外部内容中,因此在加载发生后没有内部内容。尝试使用:

$mainContentOuter.load(link + ' ' + '#content', function() {
    // Animate the height difference when loaded
    $mainContentOuter.height($mainContentInner.outerHeight());
});

想象一下,你有两个矩形A和B,其中B在A里面。如果你把B所有的东西都加载给A,那么B就没有了,但只有A,因为B里面没有B,所以A里面也没有B。我最近遇到了一个类似的问题,我花了几个小时来理解和解决它。请让我知道这是否解决了你的问题!

多亏了@thanasis,我才意识到这里发生了什么。

变量$mainContentInner在DOM中存储了对原始对象的引用。一旦页面内容被加载,这个对象就会被删除并替换为另一个对象,尽管它们很相似。

尽管它们具有相同的ID,但它们是不同的对象。为了解决这个问题,我重新定义了变量,以便针对新对象。见下文:

    // Load content
    $mainContentOuter.load(link + ' ' + linkContent, function() {
        // Redefine $mainContentInner to the new object
        $mainContentInner = $(linkContent);
        // Animate the height difference when loaded
        $mainContentOuter.height($mainContentInner.outerHeight());
    });