friendly version not working

Running into an interesting browser problem -- I've implemented jQuery to toggle a page's stylesheet link href, on click of a button, between a normal view css file and a print-friendly css file. It works, except that when the viewer goes to the print-friendly version, I call window.print() after the new link href has been applied. The print preview automatically comes up, and in the preview, certain elements that should have display:none in the print-version are visible. If you click "print", then the print comes out screwed up, just like the preview. If you cancel the print, then the page on screen is still in print-friendly mode, but everything is fine and nothing is visible that shouldn't be. And if you then right-click and select "Print..." the preview displays as it should, and everything prints as it should.

This has to be a browser thing, because it's only happening in Chrome, not in FF.

This is the function that gets called whenever the button is clicked:

$('#printOnlyBtn').click(function(){
    if ($('#mainStylesheetLink').attr('href') == 'normal.css' {
        //switch to print-friendly css file and print
        doPrint();
    }
    else {
        //switch back to normal css file
        $('#mainStylesheetLink').attr('href', 'normal.css');
    }
});

function doPrint(){
    $('#mainStylesheetLink').attr('href', 'printFriendly.css');
        window.print();
    }

One solution is to take out the call to window.print(); just put the page in print-friendly mode with one button, and then have another button the user must click to actually print the page. But I'd prefer to keep it a one-click process if possible.


I'd recommend abandoning your approach of linking to a css file. Instead, try using a @media print { ... } declaration in your css. Include your print-specific styling within this block. There's great documentation at https://developer.mozilla.org/en-US/docs/Web/CSS/@media.


I solved the problem just using setTimeout(). I figured there's a race condition or something like that, so I just delayed the call to window.print() by 100 ms:

function doPrint(){
    $('##mainStylesheetLink').attr('href', '#printFriendly.css');
    setTimeout(window.print, 100);
}

I actually tried that before, but I coded it as below, forgetting that the code to be executed after delay needs to be passed into setTimeout() as a callback function without the parens, else it gets called immediately:

setTimeout(window.print(), 100);
链接地址: http://www.djcxy.com/p/82590.html

上一篇: 下载rpivotTable输出闪亮的Dasboard

下一篇: 友好的版本不起作用