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

如何修改代码使图片裁剪预览功能兼容jQuery 3.5.1.min.js

问题原因

jQuery 3.5.0版本对HTML解析逻辑做了安全补丁,修复了XSS注入漏洞,html()方法对直接拼接在iframe src属性中的Data URI做了严格的安全拦截,这就是代码在jQuery 3.4.1版本可正常运行、升级到3.5.1后预览失效的根本原因。

修复方案

两种修改方案均可直接兼容jQuery 3.5.1版本,根据业务场景选择即可:

方案一(推荐):替换iframe为img标签预览

单张图片预览无需使用iframe,直接用img标签完全避开jQuery安全策略限制,性能更优、兼容性更好,仅需替换.salvar按钮的点击事件逻辑:

$('.salvar').click(function() {
  const temp = recorte.cropper('getCroppedCanvas').toDataURL();
  // 直接用img标签展示裁剪后图片
  $("#some").html(`<img src="${temp}" style="width: 100%; height: auto;" alt="裁剪结果">`);
  $("#image_cropped").val(temp);
  $("#image_crop_btn").hide();
});

方案二:保留iframe的修改逻辑

如果业务必须使用iframe承载预览内容,手动创建iframe后操作其内部文档写入内容,规避html()方法的安全校验:

$('.salvar').click(function() {
  const temp = recorte.cropper('getCroppedCanvas').toDataURL();
  $("#some").empty();
  // 手动创建iframe
  const iframe = document.createElement('iframe');
  iframe.frameBorder = "0";
  iframe.style.cssText = "border:0; top:0; left:0; bottom:0; right:0; width:100%; height:100%;";
  iframe.allowFullscreen = true;
  // 追加到DOM后写入图片内容
  $("#some").append(iframe);
  const iframeDoc = iframe.contentWindow.document;
  iframeDoc.write(`<style>body{margin:0;padding:0;}</style><img src="${temp}" style="width: 100%; height: 100%; object-fit: contain;">`);
  iframeDoc.close();
  
  $("#image_cropped").val(temp);
  $("#image_crop_btn").hide();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:30:01