简体   繁体   English

如何使用 jQuery 设置 @page CSS 属性?

[英]How can I set @page CSS attributes with jQuery?

One can make a page be printed in landscape mode with可以使页面以横向模式打印

@page {size: landscape;}

But I only want a page to be printed in landscape when some conditions are met (eg when there is wide content on the page).但我只希望在满足某些条件时(例如,当页面上的内容较宽时)以横向打印页面。

How can I set this attribute with jQuery / JavaScript?如何使用 jQuery / JavaScript 设置此属性?

What doesn't work什么不起作用

$('@page')
Uncaught Error: Syntax error, unrecognized expression: @page

Your jQuery is trying to select some element named page and with invalid selector @ .您的 jQuery 正在尝试选择一些名为page并且使用无效选择器@元素。

All you need to do is add @page{size: landscape;} to CSS您需要做的就是将@page{size: landscape;}到 CSS

$('head').append('<style>@page{size: landscape;}</style>')

You can access the rule via the styleSheets collection and change its size.您可以通过styleSheets集合访问规则并更改其大小。

Here's an example: The CSS declares @page { size: landscape; }下面是一个例子:CSS 声明@page { size: landscape; } @page { size: landscape; } and then the code changes it to portrait : @page { size: landscape; } ,然后它的代码更改为portrait

 Array.from(document.styleSheets).forEach(ss => { Array.from(ss.rules || ss.cssRules).forEach(rule => { if (rule instanceof CSSPageRule) { rule.style.size = "portrait"; console.log("New rule size: " + rule.style.size); } }); });
 @page { size: landscape; }

That example keeps going to find all CSSPageRules , but if you know there's only one you could use some instead:该示例继续查找所有CSSPageRules ,但如果您知道只有一个,则可以使用some来代替:

Array.from(document.styleSheets).some(
    ss => Array.from(ss.rules || ss.cssRules).forEach(rule => {
      if (rule instanceof CSSPageRule) {
        rule.style.size = "portrait";
        console.log("New rule size: " + rule.style.size);
        return true;
      }
    })
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM