Can JavaScript change the value of @page CSS?

前端 未结 2 466
鱼传尺愫
鱼传尺愫 2020-12-02 23:22

The following CSS affects whether a page prints in portrait or landscape by default.

@page {
   size: landscape;
}

I realize that this only

相关标签:
2条回答
  • 2020-12-03 00:01

    @jasssonpet saved my butt with his answer. That being said, I changed it to be a little simpler (in my opinion).

    ** Not quite sure why it was done the way it was, but please educate me if you know. If it's just preference, then I'm sharing my code sample because someone else's preferences might align better with mine.

    // just create the style tag and set the page size
    function setPageSize(cssPageSize) {
        const style = document.createElement('style');
        style.innerHTML = `@page {size: ${cssPageSize}}`;
        document.head.appendChild(style);
    }
    
    // how to use it
    setPageSize('letter landscape');
    

    EDIT: I logged in for the first time in a while and saw @jasssonpet's answer and it makes a lot more sense to me now. In case anyone else is confused, the main benefit of his approach is 2 things:

    1. He makes use of closures so that there is only 1 style tag added to the page that can then be referenced and changed.
    2. He extends upon cssPagedMedia so that any methods added are namespaced. This way, the global namespace isn't polluted.

    Here is it in Class form (which I find easier to understand):

    class SingletonStyle {
      constructor() {
        this.style = document.createElement("style");
        document.head.appendChild(this.style);
      }
    
      apply(rule) {
        this.style.innerHTML = rule;
      }
    
      size(size) {
        this.apply("@page {size: " + size + "}");
      }
    }
    
    0 讨论(0)
  • 2020-12-03 00:10

    One simple way is to create a separate style for @page and change it:

    var cssPagedMedia = (function () {
        var style = document.createElement('style');
        document.head.appendChild(style);
        return function (rule) {
            style.innerHTML = rule;
        };
    }());
    
    cssPagedMedia.size = function (size) {
        cssPagedMedia('@page {size: ' + size + '}');
    };
    
    cssPagedMedia.size('landscape');
    
    0 讨论(0)
提交回复
热议问题