开发者

Append stylesheet link for printing triggered on jQuery click() event

开发者 https://www.devze.com 2023-04-12 19:35 出处:网络
I have one css link on the head section that has media=\'screen\' attribute, then I want to link the other css file that has media=\'print\' attribute dynamically.

I have one css link on the head section that has media='screen' attribute, then I want to link the other css file that has media='print' attribute dynamically.

and I do this for the solution.

$("div#alert").click(function(){
    $('head')
    .append("<link rel='st开发者_Python百科ylesheet' href='css/alert.css' media='print' />");
    window.print();
});

But.. When I ran that code, the output just printed based on the media='screen' css.

Then I try again with the same code, I clicked the div element and when the print dialog box appear, I clicked the cancel button, then I clicked the div element again.. then clicked the ok button this time.. the media='print' is working... So what do I have to do with the window.print()?


Maybe you are calling window.print() too early (before the print stylesheet has even been downloaded) - try this:

$("div#alert").click(function(){
    $('head')
    .append("<link rel='stylesheet' href='css/alert.css' media='print' />");
    setTimeout(function() {
        window.print();
    }, 1000);
});

A more elegant solution would be to load the stylesheet asynchronously, insert it in the head, and then call the print() function in the callback of the AJAX request.


You can use $.get and the success callback in this way:

$("div#alert").click(function(){
    $.get('css/alert.css', function (response) {
       $('head')
          .append("<style rel='stylesheet' media='print'></style>")
          .html(response);

    }).success(function () { 
        window.print();
    });
});


It looks like your javascript function is running and not letting the browser in to update the CSS.

Watch this video that explains how event loop works in Javasript. That also means that if your cycles work slowly and block the browser, you can just split them in timeouts.

My advice will be doing something like Alex is telling, to put .print in a timeout.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号