Home > Web Front-end > HTML Tutorial > js method to get the actual width and height of Html elements

js method to get the actual width and height of Html elements

不言
Release: 2018-06-05 14:39:36
Original
3530 people have browsed it

The following editor will bring you a js method to obtain the actual width and height of Html elements. The editor thinks it’s pretty good, so I’d like to share it with you now and give it as a reference. Let’s follow the editor to take a look.

The first case is that the width and height are both written in the style sheet, such as #p1{width:120px;}. In this case, the width cannot be obtained through #p1.style.width, but the width can be obtained through #p1.offsetWidth.

The second case is that the width and height are written inline, such as style="width:120px;". In this case, the width can be obtained through the above two methods.

Summary, because id.offsetWidth and id.offsetHeight regardless of whether the style is written in the style sheet or inline, it is best to use these two attributes when we obtain the width and height of the element. Note that if the attributes are not written in the inline style, they cannot be obtained through id.style.atrr.

In current front-end production, styles are rarely written directly in the style, but are always written in the style sheet. If the style you want to get does not have a corresponding one (just like #p1.style.width corresponds to #p1.offsetWidth), you can only get the attributes of the style sheet separately without using the browser. You can try searching for "JS Get Style" Properties" and the like.

Code:

var o = document.getElementById("view");
var h = o.offsetHeight; //高度
var w = o.offsetWidth; //宽度
Copy after login

Related recommendations:

js html5 implements page refreshable countdown effect



The above is the detailed content of js method to get the actual width and height of Html elements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
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