简体   繁体   English

用Javascript测量div的宽度

[英]Measure div's width with Javascript

I have two questions. 我有两个问题。 The more important one is how can I measure the width of a div? 更重要的是如何测量div的宽度? Not to get the CSS value, but in px or ems or so on. 不是获取CSS值,而是在px或ems等中。 Right now I'm doing it like this 现在我这样做

document.getElementById("menu").addEventListener("click", GetWidth);
function GetWidth() {
var ulObject=document.querySelector(".dropdown-menu");
var obtainedStyle=window.getComputedStyle(ulObject);
var ulWidth=obtainedStyle.getPropertyValue("width");
console.log(ulWidth);
}

It works to a point. 它起到了一定的作用。 The problem is that the property of width is set to auto, but might change. 问题是width的属性设置为auto,但可能会更改。 How do I get it in any usable value? 如何获得任何可用的价值?
The second question is how can I make an event handler but with a class? 第二个问题是如何使用类创建事件处理程序? The querySelector and getElementByClassName didn't work. querySelector和getElementByClassName不起作用。
I would rather avoid jQuery for now, but if it's the only option I'll take it. 我宁愿现在避免使用jQuery,但如果它是唯一的选择我会接受它。 The answer given in How do I retrieve an HTML element's actual width and height? 答案如何检索HTML元素的实际宽度和高度? doesn't work. 不起作用。 Even though I have no display:none; 即使我没有显示:没有; the offsetWidth still shows 0. offsetWidth仍显示0。

Use getBoundingClientRect : 使用getBoundingClientRect

var rect = ulObject.getBoundingClientRect();
var ulWidth = rect.width;

If you need to support IE8 and previous, you can use 如果您需要支持IE8和之前的版本,您可以使用

var ulWidth = rect.right - rect.left;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM