【问题标题】:JS: window.open - how to set Open Sans font?JS:window.open - 如何设置 Open Sans 字体?
【发布时间】:2017-08-16 15:14:27
【问题描述】:

我无法让它工作。我唯一需要的 - 将所有内容字体系列设置为'Open Sans'。这是我现在拥有的

        var popupWin = window.open('', '_blank', 'width="100%",height="100%"');
        popupWin.document.write('<html><head><link href=\'http://fonts.googleapis.com/css?family=Open+Sans\' rel=\'stylesheet\' type=\'text/css\'></head><body>' + content + '</body></html>');
        popupWin.document.body.setAttribute('style', 'font-family: \'Open Sans\' !important');
        popupWin.document.close();
        popupWin.print();
        popupWin.close();
    }

这段代码显示空白页面,但是当我删除link 属性时,内容正在显示,但带有默认系列。有什么想法吗?

附:内容变量包含一个简单的 html 标记,我试图设置样式像

&lt;div style="font-family='Open Sans'"&gt;

但没有运气。

【问题讨论】:

  • 您是从 HTTPS 选项卡打开页面吗?如果是这样,浏览器将阻止您对“http://....”的请求。尝试删除协议href=\'//fonts.googleapis.com/css?family=Open+Sans\'
  • 是的,我使用的是 HTTPS,但是如何删除协议,Open Sans 不是标准字体,我必须上传它
  • 评论告诉你怎么做。只需从 href 属性的开头删除 http:(保留斜线)即可。
  • 这只是一个空白屏幕,没有显示任何内容

标签: javascript printing font-family


【解决方案1】:

将http 更改为https。您可能还想在打印之前添加延迟。请尝试以下操作:

document.querySelector('button').onclick = function() {
  var content = document.querySelector('textarea').innerHTML;

  var popupWin = window.open('', '_blank', 'width="100%",height="100%"');
  // Popup locked by browser
  if (!popupWin) {
    console.log('Popup was blocked');
    return false;
  }
  popupWin.document.write('<html><head><link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"></head><body>' + content + '</body></html>');
  popupWin.document.body.setAttribute('style', 'font-family: "Open Sans" !important');
  setTimeout(function() {
    popupWin.document.close();
    popupWin.print();
    popupWin.close();
  }, 2000);
};
<h1>Test</h1>
<textarea>Put this on the popup page</textarea>
<button>Print</button>

【讨论】:

  • 这很奇怪,但是添加延迟后问题就消失了,您能解释一下原因吗?
  • 我认为打印功能没有等待加载资源。
  • @styfle:你的意思是这样吗? if (!popupWin) {
猜你喜欢
  • 2016-08-08
  • 2017-12-20
  • 2015-12-19
  • 2016-03-07
  • 2014-05-19
  • 2013-10-17
  • 2016-12-21
  • 2015-12-07
  • 1970-01-01
相关资源
最近更新 更多