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

如何使用JavaScript实现点击切换图片尺寸,点击缩50%再点击恢复原尺寸

原有代码问题排查

原有代码无法生效主要存在3个问题:

  • 元素选取逻辑不稳定:硬编码document.getElementsByTagName("img")[11]的索引选取图片,只要页面图片数量发生变化就会选中错误元素
  • 尺寸赋值语法错误:DOM元素的height、width属性仅支持像素数值输入,直接写50%属于非法赋值,不会生效
  • 缺少状态切换逻辑:仅实现了单次缩小的逻辑,没有记录点击状态、存储原始尺寸的逻辑,无法实现缩小/恢复的切换效果
实现方案

方案1:保留现有内联onclick写法

修改HTML中img标签的onclick参数,把当前点击的元素自身传入函数:

<article id="featuredartists">
    <h2>Featured Artists</h2>
    <div class="artistlist group">
        <ul class="group">
            <li><img src="images/artists/Barot_Bellingham_tn.jpg" alt="Photo of Barot Bellingham" onclick="func3(this)"></li>
        </ul>
    </div>
</article>

替换对应的JavaScript代码:

function func3(img) {
  // 首次点击时存储原始尺寸
  if (!img.dataset.originWidth) {
    img.dataset.originWidth = img.width;
    img.dataset.originHeight = img.height;
  }
  // 切换缩放状态
  if (img.dataset.isShrinked === 'true') {
    // 恢复原始尺寸
    img.width = img.dataset.originWidth;
    img.height = img.dataset.originHeight;
    img.dataset.isShrinked = 'false';
  } else {
    // 缩小为原尺寸的50%
    img.width = img.dataset.originWidth * 0.5;
    img.height = img.dataset.originHeight * 0.5;
    img.dataset.isShrinked = 'true';
  }
}

方案2:更规范的事件绑定写法(移除内联onclick)

首先删除HTML中img标签的onclick属性,替换为如下JavaScript代码即可:

document.addEventListener('DOMContentLoaded', function() {
  // 精准选取目标图片
  const targetImg = document.querySelector('#featuredartists .artistlist img');
  // 存储原始尺寸和状态
  const originWidth = targetImg.width;
  const originHeight = targetImg.height;
  let isShrinked = false;

  targetImg.addEventListener('click', function() {
    isShrinked = !isShrinked;
    targetImg.width = isShrinked ? originWidth * 0.5 : originWidth;
    targetImg.height = isShrinked ? originHeight * 0.5 : originHeight;
  });
});

如果需要给多个图片添加相同效果,只需修改选择器选中所有目标图片,遍历绑定点击事件即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:06:04