如何使用jQuery获取同一class的多个<input>元素的最大宽度?
使用jQuery获取同class元素的最大宽度
可以通过遍历目标元素集合,逐个获取宽度并维护最大值的方式实现,核心代码如下:
let maxWidth = 0; $('.c1').each(function() { // 获取元素的内容宽度(不含内边距、边框) const currentWidth = $(this).width(); if (currentWidth > maxWidth) { maxWidth = currentWidth; } }); console.log('最大宽度值:', maxWidth);
宽度方法说明:
width():获取元素内容区域的宽度(不含内边距、边框、外边距)outerWidth():获取元素内容+内边距+边框的宽度(不含外边距)outerWidth(true):获取元素内容+内边距+边框+外边距的总宽度
根据你的需求替换对应的方法即可。
确保DOM加载完成
如果代码放在页面头部,需要包裹在DOM就绪事件中,避免元素未加载导致无法获取宽度:
$(document).ready(function() { let maxWidth = 0; $('.c1').each(function() { const currentWidth = $(this).width(); maxWidth = Math.max(maxWidth, currentWidth); }); console.log('最大宽度值:', maxWidth); });
内容的提问来源于stack exchange,提问作者saman
相关产品推荐
相关产品推荐

