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

如何在JS调用window.print()时通过@media调整PHP输出图片尺寸

我明白你的问题了——你已经用@media print来控制打印样式,但PHP动态输出的图片因为带有内联样式,导致打印时的尺寸规则不生效,对吧?这是因为内联样式的优先级比CSS媒体查询要高,所以你的td img{ width:600px; }被图片自带的width:180px覆盖了。下面给你几个可行的解决方案:

方案1:用!important强制覆盖内联样式

这是最快速的解决方式,直接在打印媒体查询的样式里添加!important,提升规则优先级来覆盖内联样式:

@media print {
  #share-buttons { visibility: hidden; }
  #flowersButton { visibility: hidden; }
  td img{ 
    width: 600px !important; 
    height: auto !important; /* 保持图片比例不变 */
  }
}

方案2:移除内联样式,改用外部CSS管理

如果想更符合CSS最佳实践,避免内联样式带来的优先级混乱,可以修改PHP输出代码,把图片的内联style换成类名:

<? 
if ($obituary['photo'] != "" && file_exists("../photos/" . $obituary['photo'])) 
    echo"<img src='../photos/" . $obituary['photo'] . "?" . strtotime($obituary['addedon']) . "' class='obituary-photo' border='0'>";
?>

然后分别设置屏幕显示和打印的样式:

/* 屏幕显示的常规样式 */
.obituary-photo {
  height: auto;
  width: 180px;
}

/* 打印样式 */
@media print {
  #share-buttons { visibility: hidden; }
  #flowersButton { visibility: hidden; }
  .obituary-photo {
    width: 600px;
    height: auto;
  }
}

方案3:用JavaScript在打印前临时修改样式

如果你暂时无法修改后端PHP或CSS代码,可以在打印触发函数里动态调整图片尺寸,打印完成后再恢复原样:

function printFunction() {
  // 获取目标图片元素
  const targetPhoto = document.querySelector('#tdimg img');
  // 保存原有样式,方便打印后恢复
  const originalWidth = targetPhoto.style.width;
  const originalHeight = targetPhoto.style.height;
  
  // 设置打印用的尺寸
  targetPhoto.style.width = '600px';
  targetPhoto.style.height = 'auto';
  
  // 触发打印
  window.print();
  
  // 打印完成后恢复原样式(不管用户选择打印还是取消都会执行)
  targetPhoto.style.width = originalWidth;
  targetPhoto.style.height = originalHeight;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:37:37