简体   繁体   English

jQuery.append()与转换一起使用时出现异步

[英]jQuery.append() appearing async when using with transitions

it appears that, if an animation is set for the elements, the following two boxes behave differently depending on wether they have been in the dom already or have shortly been added by jQuery.append(): 似乎,如果为元素设置了动画,则以下两个框的行为会有所不同,具体取决于它们是否已经在dom中或由jQuery.append()不久添加:

jQuery(document).ready(function() {
    var el1 = jQuery("<div id='movedElement1'>moved element 1</div>");
    jQuery(document.body).append(el1);
    el1.css({
        top: 200
    });

    var el2 = jQuery("#movedElement2");
    el2.css({
        top: 200
    });
});

A full example can be found at https://jsfiddle.net/omz0w9pp/1/ . 可以在https://jsfiddle.net/omz0w9pp/1/上找到完整的示例。 Box2 moves to the new position (as intended) while box1 just appears there. Box2移到新位置(按预期),而box1仅出现在该位置。

Any idea why this is happening, how to prevent it or, if that's not possible, get a callback when the element is ready to be moved/animated? 是否知道为什么会发生这种情况,如何防止这种情况发生,或者在无法进行元素移动/动画处理时(如果不可能的话)获得回调?

try calling $(el1).offset() right before setting its css. 尝试在设置CSS之前$(el1).offset()调用$(el1).offset() https://jsfiddle.net/omz0w9pp/2/ https://jsfiddle.net/omz0w9pp/2/

jQuery(document).ready(function() {
    var el1 = jQuery("<div id='movedElement1'>moved element 1</div>");
    jQuery(document.body).append(el1);
    $(el1).offset();
    el1.css({
        top: 200
    });

    var el2 = jQuery("#movedElement2");
    el2.css({
        top: 200
    });
});

What is happening is that the JavaScript fires quicker than the page can refresh/repaint, so the css transition doesn't get a chance to fire. 发生的情况是,JavaScript的启动速度比页面刷新/重新绘制的速度快,因此CSS过渡没有启动的机会。

Calling .offset() forces a page repaint, and so when you tweak the css the transition is aware of the value change and fires accordingly. 调用.offset()强制页面重新绘制,因此,当您调整CSS时,过渡会意识到值的更改并相应地触发。

You could also use a timeout (or anything that forces a redraw) but I like this method. 您也可以使用超时(或任何强制重画的内容),但我喜欢这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM