Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

javascript - 如何检索HTML元素的实际宽度和高度?(How do I retrieve an HTML element's actual width and height?)

Suppose that I have a <div> that I wish to center in the browser's display (viewport).

(假设我有一个<div> ,希望在浏览器的显示(视口)中居中。)

To do so, I need to calculate the width and height of the <div> element.

(为此,我需要计算<div>元素的宽度和高度。)

What should I use?

(我应该使用什么?)

Please include information on browser compatibility.

(请提供有关浏览器兼容性的信息。)

  ask by snortasprocket translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use the .offsetWidth and .offsetHeight properties.

(您应该使用.offsetWidth.offsetHeight属性。)

Note they belong to the element, not .style .

(请注意,它们属于元素,而不是.style 。)

var width = document.getElementById('foo').offsetWidth;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...