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

使用JavaScript调整3张图片尺寸 无ID且无法添加ID的实现方案

问题原因

你当前使用的document.querySelector()仅会返回匹配到的第一个img元素,因此只能修改单张图片的尺寸,无法命中所有目标图片。

解决方法

场景1:需要修改页面内所有图片的宽度

使用document.querySelectorAll('img')获取页面全部图片节点,遍历后统一设置宽度即可:

// 获取页面所有img元素
const images = document.querySelectorAll('img');
// 遍历设置宽度
images.forEach(img => {
  // 方式1:设置原生width属性,单位默认px
  img.setAttribute('width', 50);
  // 方式2:通过style设置,优先级更高,可避免被其他CSS规则覆盖
  // img.style.width = '50px';
});

场景2:仅需要修改某个容器内的3张图片

如果目标图片是放在特定父容器内(比如你能确定父容器的类名/标签名),可以缩小选择器范围,避免误改其他位置的图片,示例:

// 假设目标图片都在class为article-content的容器内,替换成你实际的父容器选择器即可
const targetImages = document.querySelectorAll('.article-content img');
targetImages.forEach(img => img.style.width = '50px');

内容的提问来源于stack exchange,提问作者bigwall

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:06:03