You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:09:55