Home  >  Article  >  Web Front-end  >  How to set the width and height of an element in javascript

How to set the width and height of an element in javascript

藏色散人
藏色散人Original
2021-11-15 15:22:374229browse

How to set the width and height of elements in javascript: 1. Get the width and height of the html element; 2. Set the width and height of the element through "main.style.width" and "main.style.height".

How to set the width and height of an element in javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

How to set the width and height of elements with javascript?

JS Get the width and height of html elements and set the width and height

Get the width and height of the browser:

 var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Two ways to get the width and height of html elements

// 首先是取到元素
var main = document.getElementById('main');
// 第一种方式
var mainWidth = main.offsetWidth,
mainHeight = main.offsetHeight;
// 第二种方式
var mainWidth2 = main.style.width,
mainHeight2 = main.style.height;

The difference between the two methods is that the first method can get the width and height under any circumstances, while the second method can only get the width and height defined in html, but not the width and height defined by css.

Set width and height

main.style.width = "120px";
main.style.height = "130px";

There is and is the only method. The following method is not feasible. Firefox test.

main.style.offsetWidth = "120px";
main.style.offsetHeight = "130px";

Recommended study: "javascript basic tutorial"

The above is the detailed content of How to set the width and height of an element in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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