如何创建一个允许JavaScript检测高度的元素

时间:2017-01-27 18:51:43

标签: javascript html css

我想在我的网页上创建一个元素(div),但不要使用position:absolute;

div必须是页面的100%,但我需要能够通过JavaScript获取实际高度(以像素为单位)。

如何使用CSS设置此样式以允许此JavaScript功能?拜托,没有JQuery

1 个答案:

答案 0 :(得分:3)

见内联评论:



// Create a <div> dynamically
var div = document.createElement("div");

// Attach CSS class to div
div.setAttribute("class", "height100");

// Add to the document
document.body.append(div);

// Get the actual height of the element:
console.log("The height of the div is: " + window.getComputedStyle(div).height);
&#13;
.height100 { height: 100vh; }
&#13;
&#13;
&#13;