【问题标题】:jquery width get 0jQuery宽度得到0
【发布时间】:2013-07-29 16:17:24
【问题描述】:

jquery 函数 width() 总是返回 0。这是我的布局

<div class="entity" id="id-@user.id">
   <div class="inactive">
      <div class="touch-header">                                               
         <div>
            <small>@user.name<br>@user.surname</small>
         </div>

         <div role="button" data-toggle="modal" id="home_office_id-@user.id" class="home_office_log pull-right" style="margin-top: -2.2%;text-align:center; margin-right: 2px;opacity: 0.8;width: 50px; height: 50px;position: absolute; margin-left: 4.9%;z-index: 1;">
           ...
         </div>
      </div>
   </div>
</div>

然后我有 javascript 代码,我想通过 animate 方法将标签的内容 移动到 div class="entity"

的中间
var lab = $('div.entity#id-' + userId).children().
        children().children().children('small');                         
lab.css('position', 'relative').animate({
    left: $('.entity#id-'+userId).width() - lab.width() / 2 - 15
}, 500);

但函数 width() 在这两种情况下都返回 0。我该怎么办?

【问题讨论】:

  • .children().children().children().children('small'); -- .find("small")
  • 你必须显示生成的 HTML,我假设 @user-id 被替换,因为 jQuery 告诉我 Uncaught Error: Syntax error, unrecognized expression: div.entity#id-@user.id
  • @JuanMendes - 这可能是 asp.net MVC 剃须刀代码
  • 是的,它是从java框架生成的。只要放任何数字,它不会改变任何东西。并为变量 userId 使用相同的数字
  • @ParvSharma 我不在乎它是什么服务器端框架。为了清楚问题,您应该显示浏览器看到的实际 HTML。同时告诉我们userId 是什么。你提出的问题越好,就越有可能有人会提供帮助,如果我们必须继续挖掘,我们就会停止寻找,就像我刚才所做的那样

标签: javascript jquery width


【解决方案1】:

问题解决了,这一切都是为了生成另一个页面作为不同选项卡的克隆,所以即使布局只生成了一次,jquery 对象也会在 DOM 中创建两次。并且该选择器返回了 2 个对象,但其中只有一个对象正确设置了宽度属性。无论如何感谢回复,尤其是@Juan

【讨论】:

    【解决方案2】:

    试试innerWidthouterWidth,它们实际上是计算值,width AFAIK 只返回 CSS 中的值。

    【讨论】:

    • 回答“试试这个”应该是评论。如果您知道这是问题所在,那么它应该是一个答案。 $.width 不返回 CSS 中设置的值,它使用计算样式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多