【问题标题】:trying to print iframe content but print the whole page instead尝试打印 iframe 内容但打印整个页面
【发布时间】:2016-06-19 08:54:28
【问题描述】:

我有我在我的 html 页面中动态创建的 iframe 和打印按钮,点击事件 打印 iframe 的内容 但不幸的是,它打印了整个页面 但经过长时间的搜索 我找到了一些解决方案,例如在触发打印事件之前关注 iframe 但它似乎不适用于 IE 和 MS Edge 它适用于 Chrome 唯一适合我的解决方案是打开新窗口并在其中复制 iframe outerhtml 并在新窗口中加载内容后触发打印事件 然后在用户执行打印或取消操作后立即关闭新窗口 但是这个解决方案看起来对用户不友好 那么在 IE 和 Edge 中打印 iframe 内容有什么解决方案吗

 <html>
<head>
<title>IFrame Printing Issue</title>

<script type="text/javascript">
  var g_iFrame;

  function onLoad()
  { 
     g_iFrame = document.createElement("iframe");
     g_iFrame.id = "testFrame";
     var style = g_iFrame.style;
     style.border = "1px solid black";
     style.width = "300px";
     style.height = "200px";

     document.body.appendChild(g_iFrame);
  }

  function setIFrameSrc()
  {
     g_iFrame.src = "Test.htm";
  }

  function printIFrameContent()
  {
  window.frames["testFrame"].contentWindow.focus();
  window.frames.testFrame.contentWindow.print();
  }
</script>
</head>

<body onload="onLoad();">
<button type="button" onclick="setIFrameSrc();">Set IFrame Src</button> 
 <br /> 
<button type="button" onclick="printIFrameContent();">Print IFrameContent</button>
<br /> 

 <div style="border: 1px solid black; width: 300px; height: 200px;">
  This is to test printing the content of an IFrame whose src is set dynamically.
</div> 
</body>
</html>

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    你可以先检查一下用户代理是不是IE:

    function printIFrameContent()
    {      
      var ua = window.navigator.userAgent;
      var msie = ua.indexOf ("MSIE ");
      var iframe = document.getElementById("testFrame");
    
      if (msie > 0) {
          iframe.contentWindow.document.execCommand('print', false, null);
      } else {
          iframe.contentWindow.print();
      }
    }
    

    在 SO 上引用了类似的答案:https://stackoverflow.com/a/19639241/1500851

    【讨论】:

    • 当我从 IE 打开测试时,此方法似乎无法识别 IE msie 的值保持 -1
    • 您可以使用字符串"Trident" 来检查IE,使用"Edge" 来检查Edge
    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多