javascript - 附加到另一个 div 后获取 JQuery .height() 返回 0

标签 javascript jquery html

我正在尝试创建一个只有在向其附加文本后高于特定高度时才可滚动的 div。我使用 jquery 检查高度,它每次都返回零。有什么建议吗?

HelpOverlay.prototype.buildContent = function(helpMappings){
this.content = $('<div class="content"></div>');
var table = $('<table></table>');
table.append($('<tr><td class="key"><h3>Key</h3></td><td class="command"><h3>Command</h3></td></tr>'));
this.content.append(table);
for (var whichCategory = 0; whichCategory < helpMappings.categories.length; whichCategory++) {
    var category = helpMappings.categories[whichCategory];
    var categoryDiv = $('<div class="category">' + category.category + '</div>');
    this.content.append(categoryDiv);
    var categoryTable = $('<table></table>');
    for (var whichMapping = 0; whichMapping < category.mappings.length; whichMapping++) {
        var mappings = category.mappings[whichMapping];
        var row = $('<tr></tr>');
        var keyCell = $('<td class="key">' + mappings.key + '</td>');
        var commandCell = $('<td class="command">' + mappings.command + '</td>');
        row.append(keyCell);
        row.append(commandCell);
        categoryTable.append(row);

    }
    this.content.append(categoryTable);
}

this.helpOverlay.append(this.content);
console.log(this.content.height());
}

console.log(this.content.height()) 返回零。

最佳答案

引用这一行:

this.helpOverlay.append(this.content);

this.helpOverlay 是否已经是 DOM 的一部分?任何未插入到 DOM 中的元素将返回 0 的高度和宽度,直到它被插入。

编辑:

this.content.css( 'display', 'none' ).appendTo( 'body' );
var dims = { 'height': this.content.height( ),
             'width':  this.content.width( ) };
this.content.detach( );

关于javascript - 附加到另一个 div 后获取 JQuery .height() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272842/

相关文章:

javascript - jQuery AutoComplete 在第一次使用后显示在元素后面

javascript - 内部ajax从for循环jquery获取递增变量

javascript - 带预览和删除选项的图像上传 - Javascript/Jquery

JavaScript 错误 : Uncaught TypeError: Cannot read property 'addEventListener' of null

javascript - 等待两个异步函数

javascript - 如何在javascript中更改将对象属性之一传播到另一个对象的数组

javascript - 如何在 jQuery 中用 div 包装元素?

javascript - 如何在以下图像之间添加下一个选项?

javascript - 无法在 jQuery 中为 'data' 标记设置 'Object' 属性。 [仅限 IE8]

javascript - 如何根据元素类将元素元素属性附加到span