踩到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...

21,081 Responses

  1. CyrilDiz表示:

    Astherus: Your Partner in Decentralized Finance Innovation
    Astherus offers a groundbreaking platform that combines blockchain technology with powerful financial tools. Whether you’re a seasoned investor or new to the world of DeFi, Astherus provides a secure, transparent, and efficient solution for managing assets. https://astherus.org

    Why Astherus?

    Trustworthy Technology: Blockchain ensures transparency and security.
    Innovative Features: Advanced tools tailored for DeFi users.
    User-Centric Design: Accessible, intuitive, and adaptable to all needs.
    Discover the next generation of decentralized finance with Astherus!

  2. Richardcex表示:

    MachFi: Revolutionizing DeFi with Sonic Chain.

    MachFi is leading the way in decentralized finance (DeFi), offering a next-gen borrow-lending platform on the Sonic Chain. Our platform supports customizable trading strategies, giving users more control over their assets in a secure, decentralized ecosystem. visit to https://machfi.net/

    Why Choose MachFi?

    – Decentralized: Powered by the Sonic Chain for transparency and security.
    – Flexible Borrow-Lending: Tailored to your financial goals with custom trading strategies.
    – Innovative Technology: Harness the power of the latest blockchain technology to maximize yields.

    Start your journey with MachFi today and experience the future of DeFi!

  3. JustinTam表示:

    zithromax order online uk: ZithroPharm – zithromax 500

  4. Briantrozy表示:

    amoxicillin 500: amoxicillin order online no prescription – generic amoxicillin

  5. BrandonJag表示:

    3626 doxycycline: online doxycycline – doxycycline 200 mg capsules

  6. BrandonJag表示:

    where to buy generic clomid without dr prescription: ClmHealthPharm – generic clomid without insurance

  7. Briantrozy表示:

    zithromax online australia: zithromax buy online no prescription – zithromax online usa no prescription

  8. Roberttic表示:

    http://doxhealthpharm.com/# doxycycline 100mg tablets cost

  9. Briantrozy表示:

    zithromax coupon: zithromax 500 mg lowest price online – buy zithromax no prescription

  10. Richardcex表示:

    Why MachFi is a Game Changer in DeFi.

    With MachFi, DeFi on the Sonic Chain reaches new heights. Our unique borrow-lending platform allows users to create custom trading strategies that suit their needs and optimize performance. visit to https://machfi.net/

    Why MachFi?

    – Security: Built on the Sonic Chain’s robust blockchain technology.
    – Flexibility: Custom strategies for lending and borrowing.
    – Efficiency: Fast, reliable transactions with lower fees.

    Experience the next generation of DeFi with MachFi.

  11. Roberttic表示:

    https://clmhealthpharm.com/# can you get generic clomid pills

  12. BrandonJag表示:

    buy zithromax online: Zithro Pharm – zithromax 250 mg

  13. Briantrozy表示:

    order clomid price: ClmHealthPharm – can i buy cheap clomid price

  14. BrandonJag表示:

    doxycycline 25mg: Dox Health Pharm – buy doxycycline tablets 100mg

  15. Roberttic表示:

    http://clmhealthpharm.com/# how to get cheap clomid pills

  16. VirgilBlawl表示:

    amoxicillin 500mg capsules Amo Health Pharm amoxicillin order online

  17. JustinTam表示:

    amoxicillin online canada: amoxicillin buy canada – amoxicillin order online

  18. BrandonJag表示:

    price of amoxicillin without insurance: generic amoxicillin cost – amoxicillin 500mg buy online uk

  19. Owyjer表示:

    clavulanate cost – buy ketoconazole paypal cymbalta cost

  20. JustinTam表示:

    over the counter amoxicillin canada: Amo Health Pharm – can i buy amoxicillin over the counter

  21. BrandonJag表示:

    buy cheap zithromax online: zithromax for sale 500 mg – generic zithromax 500mg

  22. BrandonJag表示:

    doxycycline tablet price in india: buy online doxycycline – doxycycline online usa

  23. VirgilBlawl表示:

    doxycycline 150 mg cost comparison Dox Health Pharm doxycycline 200 mg pill

  24. Roberttic表示:

    http://clmhealthpharm.com/# where to get clomid without insurance

  25. Roberttic表示:

    https://clmhealthpharm.com/# can you get generic clomid online

  26. BrandonJag表示:

    how to buy doxycycline in uk: DoxHealthPharm – buying doxycycline online in usa

  27. JustinTam表示:

    doxycycline 50 mg price: Dox Health Pharm – doxycycline capsule price

  28. BrandonJag表示:

    zithromax 1000 mg pills: Zithro Pharm – zithromax buy online no prescription

  29. JustinTam表示:

    over the counter amoxicillin canada: amoxicillin azithromycin – buy amoxicillin 500mg

  30. GilbertNet表示:

    Хватит играть вслепую! Забудьте о проигрышах и разводах!

    Приветствуем в телеграм-канале, где РЕЙТИНГ казино становится вашим надежным проводником в мире азарта!

    В 2025 году онлайн-казино расцветают, но как найти среди них лучшие, честные и надежные? Мы сделали это за вас!

    Здесь вы найдете:

    ТОП самых популярных и официальных онлайн казино с лицензией.
    Обзоры, которые помогут найти официальное зеркало для входа на официальный сайт. Больше не нужно искать рабочее!
    Эксклюзивные промокоды и щедрые бонусы, включая бездепозитный бонус, чтобы играть бесплатно!
    Подробный анализ игровых автоматов, слотов и шансов сорвать джекпот!
    Инструкции, как правильно пройти регистрацию и начать играть в интернете на реальные деньги.
    Возможность скачать приложение казино для игры в любое время и в любом месте.
    Только честные и надежные казино, проверенные экспертами “Шаосин”!
    Мы поможем вам:

    Избежать мошенников.
    Найти самые выгодные предложения.
    Сорвать большой куш!
    Не тратьте время на поиски! Подписывайтесь сейчас и начните играть с умом!

    https://t.me/s/reyting_kazino_top

    Станьте профессионалом в мире онлайн-казино!

發佈留言

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