js obtains the actual width height position and other information of the scaled image

  • 2021-07-26 06:40:23
  • OfStack

In the project, the actual display size of the picture is judged. The picture may be scaled, so the actual display width and height cannot be obtained through various common width and height (all of which are the natural width or literal width of the image, not the actual display result)

I didn't find it in Baidu for a big circle on the Internet. I accidentally found two very convenient methods this morning:

object. getClientRects (); And object. getBoundingClientRect ();

You can easily obtain the absolute position of the current element (excluding scrollLeft and scrollTop, add them separately if necessary) and the actual width and height displayed

Differences between getClientRects and getBoundingClientRect

getClientRects returns a collection of TextRectangle, which is the TextRectangleList object.

getBoundingClientRect returns 1 TextRectangle object, and TextRectangle object can be returned even if there is no text in DOM.

Browser differences:

getClientRects and getBoundingClientRect are supported by all browsers except safari and firefox 2.0.

firefox 3.1 adds width and height to TextRectangle.

There are some differences between ie and non-ie browsers when using getClientRects, and ie has a wide range of TextRectangleList. However, the range of non-ie acquisition is relatively small, and only display: inline objects can obtain TextRectangleList, such as em, i, span and other tags.

At least Chrome 2 +\ Safari 4\ Firefox 3.5\ 0pera 9.63 + has been tested to support the getBoundingClientRect method.

For browser compatibility, getBoundingClientRect is now used most often to get the viewport coordinates of an element element.

MDN Detailed introduction to getBoundingClientRect: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect


Related articles: