如何在没有jQuery的情况下获得实际高度

时间:2017-05-09 06:52:46

标签: javascript html css

var test = document.getElementById('test');
console.log(test.offsetHeight);
<div style="height: 30px;" id="test">
  <p>ffffffffff</p>
  <p>gggggggggg</p>
  <p>aaaaaaaaaa</p>
  <p>dddddddddd</p>
</div>
正如您所看到的,test div中的内容为overflow且超过30px:那么如何获得准确的高度?

5 个答案:

答案 0 :(得分:2)

$("#target1").submit(function(e) {
  e.preventDefault();
  var x = document.getElementById("input").value;
  var url = "https://en.wikipedia.org/w/api.php?origin=*&action=query&format=json&prop=revisions&list=search&titles=&rvprop=content&srsearch=" + x;
  var the = function(teh) {
    $("#target2").text(teh.continue.continue);
  }
  $.getJSON(url, the);
});
var test = document.getElementById('test');
alert(test.scrollHeight);

尝试<div style="height: 30px;" id="test"> <p>ffffffffff</p> <p>gggggggggg</p> <p>aaaaaaaaaa</p> <p>dddddddddd</p> </div>

答案 1 :(得分:0)

试试这个:

window.getComputedStyle(document.getElementById('test')).height

答案 2 :(得分:0)

尝试:

var test = document.getElementById('test');
alert(test.clientHeight);

答案 3 :(得分:0)

试试这个。

var offsetHeight = document.getElementById('test').offsetHeight;

答案 4 :(得分:0)

您可以使用.clientHeight.offsetHeight;

有什么区别?

.clientHeight包含填充。

.offsetHeight包括填充,滚动条和边框。

var clientH = document.getElementById('test').clientHeight;
var offsetH = document.getElementById('test').offsetHeight;


console.log(clientH);
console.log(offsetH);
<div style="height: 30px;" id="test">
  <p>ffffffffff</p>
  <p>gggggggggg</p>
  <p>aaaaaaaaaa</p>
  <p>dddddddddd</p>
</div>