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

如何通过输入框修改textarea中iframe的参数值?

动态修改iframe的颜色、宽度和高度参数

我来帮你搞定这个需求!先指出你现有代码里的一个小问题:jQuery选择器需要加#才能选中ID为iframe_url的textarea,也就是应该写成$("#iframe_url").val(),否则获取不到值。接下来我们一步步实现完整的功能,不仅能修改textarea里的iframe代码,还能实时更新页面上渲染出来的iframe效果:

完整代码实现

<p>
  <label for="color">Choose a color</label>
  <input type="color" name="color" id="color" value="#f5f5f5">
</p>
<p>
  <label for="width">Change width</label>
  <input type="text" name="width" id="width" value="650">
</p>
<p>
  <label for="height">Change height</label>
  <input type="text" name="height" id="height" value="600">
</p>
<textarea id="iframe_url" name="iframe_url" rows="3">
<iframe id="widget" src="http://domain.tld?e=1&color=#f5f5f5" width="650" height="600"></iframe>
</textarea>
<!-- 用来预览修改后的iframe -->
<div id="iframe-preview">
  <iframe id="widget-preview" src="http://domain.tld?e=1&color=#f5f5f5" width="650" height="600"></iframe>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
  // 获取初始值并去除多余空白
  let iframeHtml = $("#iframe_url").val().trim();
  
  // 颜色选择框事件:修改src中的color参数
  $("#color").on("change", function() {
    const newColor = $(this).val();
    // 正则匹配并替换src里的color参数值
    iframeHtml = iframeHtml.replace(/color=#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/, `color=${newColor}`);
    updateIframeContent();
  });
  
  // 宽度输入框事件:实时修改iframe的width属性
  $("#width").on("input", function() {
    const newWidth = $(this).val().trim();
    if (newWidth) {
      iframeHtml = iframeHtml.replace(/width="\d+"/, `width="${newWidth}"`);
      updateIframeContent();
    }
  });
  
  // 高度输入框事件:实时修改iframe的height属性
  $("#height").on("input", function() {
    const newHeight = $(this).val().trim();
    if (newHeight) {
      iframeHtml = iframeHtml.replace(/height="\d+"/, `height="${newHeight}"`);
      updateIframeContent();
    }
  });
  
  // 通用更新函数:同步textarea内容和预览iframe
  function updateIframeContent() {
    // 更新textarea里的iframe代码
    $("#iframe_url").val(iframeHtml);
    // 更新页面上的预览iframe属性
    const $previewIframe = $("#widget-preview");
    // 从iframe代码中提取src、width、height值
    const srcMatch = iframeHtml.match(/src="([^"]+)"/);
    const widthMatch = iframeHtml.match(/width="([^"]+)"/);
    const heightMatch = iframeHtml.match(/height="([^"]+)"/);
    
    if (srcMatch) $previewIframe.attr("src", srcMatch[1]);
    if (widthMatch) $previewIframe.attr("width", widthMatch[1]);
    if (heightMatch) $previewIframe.attr("height", heightMatch[1]);
  }
});
</script>

关键细节说明

  1. 选择器修正:用$("#iframe_url")正确定位textarea元素,确保能读取和修改其中的iframe代码。
  2. 实时响应:宽度和高度输入框绑定input事件,用户输入时就能同步更新,不用等待输入完成。
  3. 正则替换:用正则表达式精准匹配需要修改的参数,避免破坏iframe代码的其他部分。
  4. 双向同步:修改后同时更新textarea的代码和预览iframe,用户既能拿到修改后的代码,又能实时看到效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:20:52