简体   繁体   中英

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'. I have tried element.style.width but didn't work because it returned 'auto'. 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. So, does anybody know an equivalent methos for jquery width()?

Thanks.

jQuery uses...

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.

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.

Wasted 2 hours on this.
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.

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 代码有点复杂。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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