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

藏色散人
Release: 2021-11-15 15:22:37
Original
4286 people have browsed it

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;
Copy after login

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;
Copy after login

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";
Copy after login

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

main.style.offsetWidth = "120px"; main.style.offsetHeight = "130px";
Copy after login

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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!