【问题标题】:Delay before javascript executesjavascript执行前的延迟
【发布时间】:2016-08-18 01:33:33
【问题描述】:

我正在使用以下 javascipt 动态居中文本。

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

但是,当我加载页面时,文本会在快速居中之前出现在其未居中的位置。如何使文本立即居中?

【问题讨论】:

  • 使用纯 CSS 而不是 JS 代码的 flex。
  • 为什么不为此设置 CSS 规则而不是使用 JavaScript?
  • 为什么不使用 css 进行样式设置?

标签: javascript html


【解决方案1】:

一个选项是 Aurora0001 链接,隐藏内容然后在 JS 运行时显示它。另一种是在 html 元素之后有 script 标签。所以你不需要准备好文档,它会立即运行:

<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 加载到 head 标记中或文档中此点之前的某个位置,应该可以正常工作。但实际上我会建议在 CSS 中执行此操作,根据 cmets。

【讨论】:

    【解决方案2】:

    $(function(){}) 是简写或$(document).ready(); 您的代码在文档准备好后执行,而不是立即执行。正如其他人所提到的:使用 css 会更有意义,并且可以立即居中。

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多