$(document).ready()启动得太早 [英] $(document).ready() fires too early

查看:102
本文介绍了$(document).ready()启动得太早的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我需要知道一个元素的宽度与javascript,我的问题是,该函数的启动太早,宽度变化时,css被特别地应用。据我所知,$(document).ready()函数在文档完成后被触发,但似乎不起作用。

So, I need to know the width of an element with javascript, the problem I have is that the function fires too early and the width changes when the css is tottally applied. As I understood, the $(document).ready() function was fired when the document is completed, but it doesn't seem to work like that.

无论如何,我确信使用代码我的问题将被理解(这是一个简化的例子):

Anyways, I'm sure that with the code my problem will be understood (this is a simplified example):

<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Parisienne' rel='stylesheet' type='text/css'>

    <style type="text/css">
        #target {
            font-family: 'Parisienne', cursive;
            float: left;
        }
    </style>
</head>
<body>
    <div id="target">Element</div>
</body>
</html>

<script type="text/javascript">
    $(document).ready(function(){
        console.debug($('#target').outerWidth());
        alert('hold on');
        console.debug($('#target').outerWidth());
    });
</script>

我想知道#target div的宽度,问题是在之前执行的代码该警报提供与之前不同的输出,大概是因为字体未完全加载,并且使用默认字体测量div。

I want to know the width of the #target div, the problem is that the code that's executed before the alert gives a different output than the one after, presumably because the font is not fully loaded and it's measuring the div with the default font.

它的工作原理与我预期的Google Chrome,但它不在IE和Firefox上。

It works as I expect in Google Chrome, but it doesn't on IE and Firefox.

推荐答案

如果您依赖外部内容已经加载(例如图像,字体),您需要使用window.load事件

If you rely on external content to be already loaded (e.g. images, fonts), you need to use the window.load event

$(window).load(function() {
    // code here
});

这些事件的行为在这篇文章

这篇关于$(document).ready()启动得太早的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆