jQuery width()没有在生成内容的div上返回正确的值 [英] jQuery width() not returning correct value on a div with generated content

查看:100
本文介绍了jQuery width()没有在生成内容的div上返回正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码,警报不会返回#main的实际大小,它总是返回#main的css宽度值,并删除%。所以在这种情况下,我在警报中得到95。如果我提醒parent()。width()我得到100.

With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped. So in this case I get 95 in the alert. If I alert parent().width() I get 100.

从.get()调用返回的数据是有时比#main宽的ul,有时候不是。内容的宽度似乎与.width()返回没有任何关系。

The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not. The width of the content doesn't seem to have any bearing on what .width() returns.

所以我的问题是,如何获得真正的像素宽度#main?

So my question is, how do I get the true pixel width of #main?

CSS:

#container {
    width: 100%;
}

#main {
    width: 95%;
    overflow: hidden; 
}

HTML:

<div id="conatiner">
    <div id="main"></div>
</div>

Javascript / jQuery:

Javascript/jQuery:

$.get('page.php', function(result) {
    $('#main').html(result);
});
alert($('#main').width();


推荐答案

我在尝试实现 jquery.autogrow-textarea 。textareas包含在尚未显示的 div 中(css display:none; )。在调试 .autogrow() javascript代码时,我发现jQuery的 .width()返回百分比值,删除'%'字符而不是计算的宽度(以像素为单位)(例如100表示​​100%,80表示80%)。

I ran into this same issue while trying to implement jquery.autogrow-textarea on textareas used for inline editing. The textareas were contained within div's that were not yet displayed (css display: none;). While debugging the .autogrow() javascript code, I discovered that jQuery's .width() was returning the percentage value with the '%' character removed as opposed to the calculated width in pixels (e.g. 100 for 100%, 80 for 80%).

以下是说明这种情况的jsfiddle: http:// jsfiddle.net/leeives/ujE6s/

Here is the jsfiddle that illustrates this scenario: http://jsfiddle.net/leeives/ujE6s/

要解决此问题,我将代码更改为 .autogrow()一旦t显示extarea。然后对 .width()的调用是准确的。

To work around this, I changed my code to .autogrow() as soon as the textarea was displayed instead. The calls to .width() were then accurate.

我不确定你是否正在使用隐藏的内容与否,但我想我会写下我的答案,以防其他人在搜索jQuery的 .width()的问题时偶然发现(就像我一样)。

I'm not sure if you're working with hidden content or not, but thought I'd write up my answer in case others stumbled upon this (like I did) while searching for an issue with jQuery's .width().

这篇关于jQuery width()没有在生成内容的div上返回正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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