简体   繁体   English

Javascript 等效于 jquery width()

[英]Javascript equivalent for jquery width()

I need to know the width in pixels of an element that has the width css property set on 'auto'.我需要知道宽度 css 属性设置为“自动”的元素的宽度(以像素为单位)。 I have tried element.style.width but didn't work because it returned 'auto'.我试过 element.style.width 但没有工作,因为它返回了“自动”。 I notices that the jquery function width() returns the length in px, but I cannot use jquery to solve this, because it is not available in my page.我注意到 jquery 函数 width() 返回以 px 为单位的长度,但我无法使用 jquery 来解决这个问题,因为它在我的页面中不可用。 So, does anybody know an equivalent methos for jquery width()?那么,有人知道 jquery width() 的等效方法吗?

Thanks.谢谢。

jQuery uses... jQuery 使用...

element.getBoundingClientRect().width

internally, it has some other stuff on top to deal with browser differences.在内部,它还有一些其他的东西来处理浏览器的差异。

It returns an elements rendered size, where as .offsetxx returns sizes according to the box model.它返回一个元素呈现的大小,而 .offsetxx 根据盒子模型返回大小。

element.getBoundingClientRect()

Is the most accurate way to get an elements "real" dimensions.是获取元素“真实”尺寸的最准确方法。

Here is a post by John Resig ( author of jQuery ) on the matter.这是 John Resig(jQuery 的作者)关于此事的帖子。

Wasted 2 hours on this.浪费了2个小时。
For my case other answers did not work so combining others answers & my findings into one post with examples, for easy reading:对于我的情况,其他答案不起作用,因此将其他答案和我的发现结合到一篇带有示例的帖子中,以便于阅读:

For an element like select , the width() in JQuery is same as clientWidth in JavaScript.对于像select这样的元素,JQuery 中的width()与 JavaScript 中的clientWidth相同。

Sample code below, including output:下面的示例代码,包括输出:

// Add jQuery library in HTML:
//   <head>
//       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//   </head>

let eleId = 'myselectid1';    // NOTE: Provide your element id below

// jQuery
console.log( $('#' + eleId).width() );

// JavaScript
let ele = document.getElementById(eleId);
console.log(ele.clientWidth);                      // 58                // includes padding into calculation
console.log(ele.offsetWidth);                      // 60                // includes border size and padding into width calculation
console.log(ele.getBoundingClientRect().width);    // 60                // includes border size and padding into width calculation
console.log(window.getComputedStyle(ele, null).getPropertyValue("width"));    // 60px     (note the px in value, you may also get values like 'auto')     // all dynamic values for all CSS properties, IE>=9
console.log(ele.style.height);                     // empty string     // if you set it earlier, you would get this
console.log(ele.innerWidth);                       // undefined        // only works on window object, not on element like select/ div - fails in older IE<9

Hope that helps.希望有帮助。

它基本上归结为.offsetWidth ,但由于跨浏览器的差异,jQuery 代码有点复杂。

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

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