踩到Window resize在Preview print的雷

最近在作案的過程中遇到一個狀況,從Art design那邊拿到的頁面,會在Window resize的時候執行某個Function,本來一切都正常,但測試到Chrome和Firefox預覽列印時發現也會Trigger這個Event,會讓在預覽列印過後的頁面發生問題,所以必須要進行修正,以下是這個案例的說明:

先在測試頁加入以下的程式,發現在預覽列印的時候會Trigger window resize event:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Preview Print Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(window).resize(function() {
            console.log("Window Resize");
        });
    </script>
</head>
<body>
<h1>Window Resize Test</h1>
</body>
</html>
Preview print trigger window resize event
Preview print trigger window resize event

網路上搜尋了一下解決方案,將Script改寫如下,可以順利解決,但不知道是不是最好的方法,如果大家有更好的也別忘了告訴我唷~

openResizeFn();

// Chorme
var print = false;
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
    if (mql.matches) {
        closeResizeFn();
    } else {
        setTimeout(openResizeFn, 2000);
    }
});

// Firefox
window.onbeforeprint = function () {
    closeResizeFn();
};
window.onafterprint = function () {
    setTimeout(openResizeFn, 2000);
};

// Common Function
function openResizeFn() {
    $(window).on("resize", windowResize);
}

function closeResizeFn() {
    $(window).off("resize", windowResize);
}

function windowResize() {
    console.log("Window Resize");
}

You may also like...

26,422 Responses

  1. The mine has been private property since 1906, and is right now utterly surrounded by Grand Canyon Nationwide Park.

  2. Stevenjaw表示:

    https://zithromax.company/# where to get zithromax
    where can i buy zithromax uk

  3. Leslie Gayle表示:

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?

  4. If you are lucky enough to have an exquisite view from an image window in your dwelling room, designate the window as your centerpiece, and compose your furnishings to make the most of it.

  5. Grout reseals the earth below the floor in order that pure ground water aquifers aren’t interrupted.

  6. Day 3, travel from Salzburg to Ljubljana & Zagreb by EuroCity practice, leaving Salzburg Hbf at 14:12, make a fast and simple change at Villach onto a connecting prepare arriving Lesce-Bled 17:50, Ljubljana 18:32 & Zagreb 20:45.

  7. NicolasLoole表示:

    https://semaglutide.win/# rybelsus price

  8. NicolasLoole表示:

    http://stromectol.agency/# ivermectin 5 mg

  9. She loved her work as an LPN as a result of she liked caring for folks, especially her family.

  10. Absent these two circumstances, capital is restricted in its skill to accumulate: it may neither produce nor sell on a mass scale.

  11. Ремонт телефонов表示:

    Профессиональный сервисный центр сервисный центр мобильных телефонов ремонт смартфона

  12. Hi there, My title is omvir singh a management put up graduate interested to begin a exhibition in my metropolis.

  13. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервис центры бытовой техники воронеж
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Long additionally performed Brandi in Boyz n the Hood.

  15. Overall, making a cinder block bench at home is an inexpensive and artistic manner so as to add seating options to any outdoor area.

  16. While such systems were as soon as widespread in cold areas, after several fires which were not controlled because of sprinkler techniques crammed with too high a share of antifreeze, the regulatory authority in the United States effectively banned new antifreeze installations.

  17. Aller (who’s a monetary adviser), a library that doubles as a guest room, and a studio for Mrs.

  18. 金融 ビル表示:

    4, 1998 in De Queen Regional Medical Heart.

  19. Matthewweind表示:

    generic zithromax azithromycin: zithromax for sale – where to buy zithromax in canada

  20. Matthewweind表示:

    cheap Rybelsus 14 mg: buy semaglutide online – Rybelsus 14 mg

  21. Michaelgax表示:

    minocycline manufacturer stromectol price ivermectin 500mg

  22. SamuelCic表示:

    https://gabapentin.auction/# neurontin price australia

  23. Michaelgax表示:

    buy stromectol pills stromectol price minocycline 100 mg without doctor

  24. SamuelCic表示:

    http://gabapentin.auction/# neurontin 100mg caps

  25. NicolasLoole表示:

    http://amoxil.llc/# amoxicillin without prescription

  26. Andrewnof表示:

    Застройщик жк резиденция лайф сэкономил на всем, низкое качество. Не рекомендую иметь дело с группой компаний паритет девелопмент. Звоните все расскажу: @dontcheatpeople – телеграмм.

  27. NicolasLoole表示:

    https://zithromax.company/# zithromax prescription in canada

  28. Hi to аll, the contents preѕent att tһis web page arе reаlly awesome fߋr people experience,
    ᴡell,keep սρ the nice work fellows.

    Stop ƅy myy blog … بهترین مشاور کنکور آنلاین و ارزان

  29. Kelvinjuile表示:


    Интернет-магазин плитки и керамики «ИнфоПлитка»

    Интернет-магазин керамической плитки и керамогранита «Infoplitka» (infoplitka.ru)
    предлагает широкий ассортимент высококачественной плитки и керамогранита от ведущих производителей.
    Мы стремимся предложить нашим клиентам только лучшее, поэтому в ассортименте представлены товары,
    отвечающие самым высоким стандартам качества и дизайна.

    Мы понимаем, что выбор керамической плитки и керамогранита – это важный этап в создании
    комфортного и стильного интерьера. Поэтому наша команда профессионалов готова помочь вам в
    подборе идеального варианта для вашего проекта. Независимо от того, нужны ли вам плитка
    для ванной комнаты, кухни, гостиной, или же керамогранит для облицовки пола, вы всегда найдете
    у нас разнообразные и актуальные коллекции, соответствующие последним тенденциям в области
    дизайна интерьеров.
    Официальный сайт «ИнфоПлитка»

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。