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

如何通过按钮点击按x%比例调整Chrome扩展popup弹窗及canvas尺寸

解决方案

核心修改逻辑如下:

  • 移除无用的CSS重载逻辑,动态修改的元素样式优先级高于静态CSS,无需重新加载样式表
  • 修正原CSS中按钮选择器的语法错误,避免按钮显示异常
  • 同步修改canvas显示尺寸和html/body容器尺寸,同时调整viewport元标签适配当前缩放比例
  • 修正原JS条件判断里的语法错误,将=>改为>=

修正后的JS代码

const adjustScreenSize = function(num) {
  const body = document.body;
  const html = document.documentElement;
  const canvas = document.getElementById('canvas');
  const viewport = document.getElementById('dimensions');
  // 修正原语法错误
  if (num >= 0.5 && num <= 2.5) {
    const finalWidth = 224 * num;
    const finalHeight = 292 * num;
    // 调整容器尺寸
    html.style.width = `${finalWidth}px`;
    html.style.height = `${finalHeight}px`;
    body.style.width = `${finalWidth}px`;
    body.style.height = `${finalHeight}px`;
    // 同步调整canvas显示尺寸
    canvas.style.width = `${finalWidth}px`;
    canvas.style.height = `${finalHeight}px`;
    // 更新viewport适配当前尺寸
    viewport.setAttribute('content', `width=${finalWidth}, height=${finalHeight}, initial-scale=1.0`);
    // 存储缩放参数
    localStorage.scale = num;
    scale = num;
  }
}

// 按钮绑定点击事件(原逻辑缺失可直接补充)
document.getElementById('plus').addEventListener('click', () => {
  const currentScale = Number(localStorage.scale || 1);
  if (currentScale < 2.5) adjustScreenSize(Number((currentScale + 0.1).toFixed(1)));
});
document.getElementById('minus').addEventListener('click', () => {
  const currentScale = Number(localStorage.scale || 1);
  if (currentScale > 0.5) adjustScreenSize(Number((currentScale - 0.1).toFixed(1)));
});

// 页面加载时读取存储的缩放比例自动应用
window.addEventListener('load', () => {
  const savedScale = Number(localStorage.scale || 1);
  adjustScreenSize(savedScale);
});

修正后的CSS代码

html, body {
  margin: 0;
  padding: 0;
  min-width: 112px;
  min-height: 146px;
  max-width: 560px;
  max-height: 730px;
  width: 224px;
  height: 292px;
  overflow: hidden; /* 避免出现多余滚动条 */
  position: relative;
}

canvas {
  width: 224px;
  height: 292px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: -1;
}

/* 修正按钮选择器错误,原#plus button写法不匹配DOM结构 */
#plus {
  position: absolute; 
  width: 20px;
  height: 20px;
  top: 25%;
  left: 10px;
  background-color: rgb(128, 128, 0);
  font-size: 20px;
  line-height: 20px;
  padding: 0;
  border: none;
  cursor: pointer;
}

#minus {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 75%;
  left: 10px;
  background-color: rgb(128, 128, 0);
  font-size: 20px;
  line-height: 20px;
  padding: 0;
  border: none;
  cursor: pointer;
}

其他说明

  • 原有HTML、manifest.json代码无需修改可直接使用,后续如果升级manifest V3,只需将browser_action字段改为action即可
  • 无需使用transform: scale属性,直接修改实际尺寸可避免弹窗留白、内容错位等问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:24:05