jQuery - 在 document.ready 之前运行函数...但不太早

发布于 2024-09-08 18:20:27 字数 1073 浏览 6 评论 0原文

我有一个页面,其中包含一个 div,在页面加载时必须通过 JS 调整其大小。为了做到这一点,我给它设置了 760px 的“默认宽度”,然后运行以下代码:

function resizeList()
{
    var wlwidth,iwidth,nwidth;
    wlwidth = document.body.clientWidth - 200 - 60;
    iwidth = 320;
    nwidth  = Math.floor(wlwidth / iwidth) * iwidth;
    $('#list').css('width',nwidth);
}

$(document).ready(function(){
    // if we're looking at a list, do the resize-thing, now and on window resize
    if (window.location.pathname.toString().split('/')[1] == "list")
    {
        resizeList();
        window.onresize = resizeList;
    }
});

但是,由于 #list div 包含大量图像,页面可能需要一段时间才能加载。因此,只有在所有内容加载完毕后,div 才会展开以填充正确的宽度。我不能只是将其从 $(document).ready 函数中取出,否则会出错,提示 document.body 未定义。

有没有办法在加载所有内容之前调整 #list div 的大小?

编辑
请参阅:http://www.google.com/images?q=whatever
他们已经成功地实现了我想要做的事情。该列表在页面加载时立即正确调整大小,然后进行填充。您可以通过调整窗口大小并观察元素平滑移动来告诉他们通过 JS 调整所有内容的大小。可悲的是,谷歌的 JS 并不是世界上最容易阅读的叹气

I have a page which contains a div which must be resized via JS when a page loads. In order to do that I give it a "default width" of 760px and then run the following code:

function resizeList()
{
    var wlwidth,iwidth,nwidth;
    wlwidth = document.body.clientWidth - 200 - 60;
    iwidth = 320;
    nwidth  = Math.floor(wlwidth / iwidth) * iwidth;
    $('#list').css('width',nwidth);
}

$(document).ready(function(){
    // if we're looking at a list, do the resize-thing, now and on window resize
    if (window.location.pathname.toString().split('/')[1] == "list")
    {
        resizeList();
        window.onresize = resizeList;
    }
});

However, the page can take a while to load as the #list div contains a lot of images. Thus, the div is only expanded to fill the correct width after all of the content has finished loading. I can't just take it out of the $(document).ready function as otherwise it errors out saying document.body is undefined.

Is there a way to resize the #list div before all of its contents have loaded?

Edit
Please see: http://www.google.com/images?q=whatever
They've achieved what I'm trying to do successfully. The list is correctly sized immediately on page load, and is then populated. You can tell they size everything via JS by resizing the window and watching the elements move smoothly. Sadly, google's JS isn't the easiest in the world to read sigh

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放肆 2024-09-15 18:20:27

它会尽快运行,$(document).ready是dom渲染完成时发生的事件。

您应该在加载时添加一个加载屏幕,然后在调整大小后可能会淡出它。

It is running as soon as it can, $(document).ready is the event that occurs when the dom is completed rendering.

You should add a loading screen onload and then possibly fade it out when after you re-size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文