Home > Web Front-end > JS Tutorial > JS method to obtain the height of an unknown DIV

JS method to obtain the height of an unknown DIV

高洛峰
Release: 2016-12-24 15:05:37
Original
1469 people have browsed it

The example in this article describes the method of obtaining the height of an unknown DIV using JS. Share it with everyone for your reference, the details are as follows:

You can get the height of the element through the clientHeight attribute of the element, such as:

var height = element.clientHeight;
Copy after login

The limitations of this approach:

1. If the display attribute of the element is set to none , then the result obtained is 0

2. In the safari browser, you need to use: element.offsetHeight to get the actual height. This is a bug of the safari browser

The following is the method provided by Prototype, which is compatible with various browsers. At the same time, the element size can be obtained correctly even when the element is hidden. For reference:

getDimensions: function(element) {
  element = $(element);
  var display = $(element).getStyle('display');
  if (display != 'none' && display != null) // Safari bug
   return {width: element.offsetWidth, height: element.offsetHeight};
  // All *Width and *Height properties give 0 on elements with display none,
  // so enable the element temporarily
  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
}
Copy after login

I hope this article will be helpful to everyone in JavaScript programming.


For more JS methods to get an unknown DIV height related articles, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template