简体   繁体   English

使用jQuery将元素插入DOM时,如何防止页面在加载时短暂跳转?

[英]When inserting elements into DOM with jQuery, how do you prevent page from briefly jumping on load?

I am moving a DIV (from a hidden iFrame) to the top of a page with jQuery, like so: 我使用jQuery将DIV(从隐藏的iFrame)移动到页面顶部,如下所示:

$(document).ready(function($) {
$('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer"));});

Whenever I reload that page, I very briefly see the original page jumping down to make room for the DIV I am inserting. 每当我重新加载该页面时,我都会非常简短地看到原始页面跳下来,为我要插入的DIV腾出空间。 Can this behavior be prevented? 可以防止这种行为吗?

What I'm doing now is give the "maincontainer" a large margin at the top with CSS that is roughly as high as the "precontainer" DIV that is inserted above it, and after that DIV is inserted, I use jQuery to remove the top margin from "maincontainer", so the jumping or flashing effect is less severe. 我现在正在做的是在CSS的顶部给“ maincontainer”一个大的空白,大约与插入其上方的“ precontainer” DIV一样高,并且在插入DIV之后,我使用jQuery删除了“ maincontainer”的上边距,因此跳跃或闪烁效果不太严重。 But there has to be a better way right? 但是必须有更好的方法吧?

I should mention that I only have access to the iFrame that I am using to manipulate the DOM of its parent (which holds "maincontainer". I can not modify the parent, so I have to do everything through the iFrame. 我应该提到的是,我只能访问用来操纵其父级DOM(持有“ maincontainer”)的iFrame。我无法修改父级,因此必须通过iFrame进行所有操作。

Instead of giving a top-margin to parent page, you can place a "placeholder" div and insert your "precontainer" to this div. 您可以在“ div”中放置“占位符” div,然后在“ div”中插入“ precontainer”,而不是在父页面上设置上边距。 This way you shouldn't see a flickering/jumping effect. 这样,您就不会看到闪烁/跳跃的效果。

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

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