【问题标题】:Print CSS: How do I open a new tab of the current page and append CSS?打印 CSS:如何打开当前页面的新选项卡并附加 CSS?
【发布时间】:2016-01-14 20:24:53
【问题描述】:

我想编写一个脚本来打开当前页面的新选项卡,同时将特定于打印的 CSS 附加到页眉。到目前为止我的 JS/jQuery:

/*jslint browser: true, devel: true */
/*global jQuery */
/*global $ */
$(document).ready(function () {
  'use strict';
  jQuery('#print').click(function (event) {
    event.preventDefault();
    $('head').append('<link rel="stylesheet" type="text/css" href="print.css">');
    return false;
  });
});

这会在当前选项卡中生成具有正确打印样式的页面。但是,当我在 $('head').append('&lt;link rel="stylesheet" type="text/css" href="print.css"&gt;'); 之前使用 window.open("&lt;myCurrentURL&gt;", '_blank'); 时,打印 CSS 不会附加到新选项卡。

我正在寻找比Open a new javascript window(.open) along with its CSS stylingwindow.open Style using css 更紧凑的解决方案。我如何将此信息传递到新标签页?

【问题讨论】:

  • 你没有。您在同一个文件中使用所有其他样式的媒体查询。developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/…
  • 或者只是&lt;link rel="stylesheet" type="text/css" href="print.css" media="print"&gt;...
  • 您是否需要支持旧版浏览器,例如 IE8?否则使用相关的 CSS 媒体查询

标签: javascript jquery css


【解决方案1】:
/*jslint browser: true, devel: true */
/*global jQuery */
/*global $ */
$(document).ready(function () {
  'use strict';
  jQuery('#print').click(function (event) {
    event.preventDefault();
    var childWindow = window.open("<myCurrentURL>", '_blank');
    $(childWindow.document).find("head").append('<link rel="stylesheet" type="text/css" href="print.css">');
    return false;
  });
});

您知道这不适用于跨域调用,除非它遵守 CORS。

【讨论】:

    【解决方案2】:

    你可以通过改变你的策略来获得结果。

    1. 当你打开窗口时传递另一个属性

    2. 在您准备好的文档中 - 检查该属性,并在需要时额外检查 url 并将 css 附加到 html 中。

    请注意 - 由于我们坚持策略,因此,回答了相同的理论策略。如果需要也可以添加代码。

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 2014-07-06
      • 2019-01-27
      • 2014-02-23
      • 2011-03-24
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多