jQuery:准备好文档并渲染后获取div宽度 [英] jQuery: get div-width after document is ready and rendered

查看:91
本文介绍了jQuery:准备好文档并渲染后获取div宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取div容器的宽度,以将另一个div中的另一个css属性设置为第一个div的宽度,我知道在页面完全加载并呈现之后.

I'm trying to get the width of a div container to set another css attribute in another div to the width of the first one, which I know after the page was fully loaded and rendered.

我有此代码:

$().ready(function() {
    doLayout();
}
function doLayout() {
    var $width = $("#sidebar").attr("width");
    $("#content").css("left", width);
}

问题是,在呈现页面之前调用了ready,因此未设置width属性(或"undefined").如何确定当前宽度?

The problem is, the ready is called before the page is rendered and thus width attribute is not set (or "undefined"). How can I determine the current width?

经过建议的更改后,我有了这个小提琴,但是其中的代码有效,但是在我的实际应用程序中却无效.所以问题出在其他地方,我想:(

After suggested changes I have this fiddle but the code there is working, but in my real application it's not. So the problem is somewhere else, I guess :(

推荐答案

使用 load 等待所有操作图片/外部内容也要加载,因为这些内容可能会更改元素尺寸:

Use load to wait for all images/external content to load as well, as these could alter element dimensions:

$(window).load(function () {
    doLayout();
});

然后要获取计算的宽度,请使用 width :

Then to get the computed width, use width:

$("#content").width(); // width in px

这篇关于jQuery:准备好文档并渲染后获取div宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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