【问题标题】:Unable to get div width/height无法获取 div 宽度/高度
【发布时间】:2026-02-10 20:30:01
【问题描述】:

我找到了一个关于如何在点击附近显示弹出窗口的简单示例:http://roshanbh.com.np/examples/popup-message/

我正在利用此按钮单击按钮,但我似乎无法获得元素的实际宽度或高度,我也不完全确定原因:

function BindObject(o)
{
    o.click(function(e)
    {
        var editor = $(this).find(".object_editor");

        console.log(editor);
        console.log(editor.height());
    });
}

这是打印到控制台的内容:

(仅供参考,在准备好文档时调用 BindObject,我也在使用 jqote,不确定它的相关性如何)

 $("#QuestContent").html($("#QuestTemplate").jqote(quest_data));
 $("#QuestContent").find(".object").each(function() {
    BindObject($(this));
 });

它显然找到了元素(由编辑器表示),但我无法确定它的宽度或高度。我确实知道显示设置为无,但那是因为我不想在有人单击按钮以显示弹出窗口之前显示它。有人知道为什么它总是为空吗?

这是css:

.object_editor{
    position:absolute;
    z-index:10;   
    width:172px;
    height:102px;
    text-align:center;
    color:#FFFFFF;
    font: 14px Verdana, Arial, Helvetica, sans-serif;
    background-color:#000000;
    display:none;
}

编辑:以及相关的 jqote 以防万一:

<!-- Object Template -->
<script type="text/x-jqote-template" id="ObjectTemplate">
    <![CDATA[
        <span class="object <%= (this.hidden ? "hiddenType" : "") %>">&nbsp;
            <input class="objectType" type="hidden" name="<%= this.key[0] %>" value="<%= this.type %>">
            <input class="objectEntry" type="hidden" name="<%= this.key[1] %>" value="<%= this.entry %>">
            <a data-emptytext="<%= object_types[this.type] %>" data-name="<%= this.key[1] %>" target="_blank" href="<%= (this.entry? whUrl(this.type, this.entry) : "#") %>" class="objectName"><%= this.name %><%= (this.entry?" ("+this.entry+")":"") %></a>&nbsp;<i class="icon-edit editObject"></i>
            &nbsp;
            <% if(this.remove) { %>
                <a href=".object" class="deleteParent"><i class="icon-trash"></i></a>
            <% } %>
        </span>

        <!-- Insert our Editor -->
        <%=$("#ObjectEditorTemplate").jqote({type: this.type, entry:this.entry}) %>
    ]]>
</script>

<!-- Object Editor Template -->
<script type="text/x-jqote-template" id="ObjectEditorTemplate">
    <![CDATA[
        <div class="object_editor">My Editor: <%= this.entry %></div>
    ]]>
</script>

【问题讨论】:

  • 添加更多信息,页面可能有多个名为 object_editor 的类,但不管这就是我使用 .find 的原因,所以我认为这无关紧要

标签: javascript jquery css jqote


【解决方案1】:

原因是因为显示设置为无。类似问题请参见this

【讨论】:

  • 我尝试使用可见性:隐藏;相反,但是当我执行 editor.width 或 editor.height 时,它仍然给我一个 null 值
  • 一旦我在 中移动它,它就正确地找到了它,我也需要上面的。谢谢!
【解决方案2】:

试试这个
$('divID').css('width');
身高也一样

【讨论】: