执行javascript之前的延迟

问题描述:

我正在使用以下javascipt动态地居中文本。执行javascript之前的延迟

$(function() { 
    $('.centre-dyn').css({ 
     'position' : 'absolute', 
     'left' : '50%', 
     'top' : '50%', 
     'margin-left' : function() {return -$(this).outerWidth()/2}, 
     'margin-top' : function() {return -$(this).outerHeight()/2} 
    }); 
}); 

但是,当我加载页面时,文本在快速居中之前会出现在其未预先确定的位置。我怎样才能让文字立即居中?

+0

使用Flex纯CSS,而不是JS代码。 – SLaks

+0

为什么不为此设置CSS规则而不是使用JavaScript? – j08691

+0

为什么你不使用CSS的样式? – randominstanceOfLivingThing

一个选项与Aurora0001链接,隐藏内容然后在JS运行后显示。另一种方法是在HTML元素后面添加脚本标记。所以你不需要的文件准备好,它会立即运行:

<div class="centre-dyn"></div> 
<script> 
    $('.centre-dyn').css({ 
     'position' : 'absolute', 
     'left' : '50%', 
     'top' : '50%', 
     'margin-left' : function() {return -$(this).outerWidth()/2}, 
     'margin-top' : function() {return -$(this).outerHeight()/2} 
    }); 
</script> 
提供的jQuery

头标记加载或文档中这点在什么地方,应该很好地工作。但我真的会建议在CSS中这样做,而不是按照评论。

$(function(){})是简写或$(document).ready();一旦文档准备就绪,您的代码就会执行,而不是立即执行。正如其他人所提到的那样:使用CSS会更有意义,并且可以立即集中。

例如:

.centre-dyn { 
position: absolute; 
left: 50%; 
top: 50%; 
transform: translate(-50%, -50%); 
}