jQuery - 在 document.ready 之前运行函数...但不太早
我有一个页面,其中包含一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它会尽快运行,
$(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.