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

7,502 Responses

  1. Hosting_smkl表示:

    Почему стоит выбрать хостинг в Беларуси бесплатно?, преимущества и особенности.
    Какой хостинг в Беларуси бесплатно выбрать?, советы и рекомендации.
    RAIDHOST, HOSTERO, TUT.BY: лучшие бесплатные хостинги в Беларуси, характеристики и отзывы.
    Как перенести сайт на бесплатный хостинг в Беларуси?, техническая документация.
    Безопасность сайта: SSL на хостинге в Беларуси бесплатно, характеристики и обзор.
    Простая инструкция: создание сайта на бесплатном хостинге в Беларуси, инструкция и рекомендации.
    Биржа хостинга в Беларуси: преимущества и особенности, обзор и сравнение.
    Хостинг Минск https://gerber-host.ru/ .

  2. plintus_uwkn表示:

    Ключевые критерии при выборе теневого плинтуса
    теневой плинтус в интерьере теневой плинтус в интерьере .

  3. 비아그라 대체 약품
    비아그라 대체 약품 추천 – 효과적인 대안은?

  4. Opened my eyes to new perspectives, and here I was thinking I’d seen it all.

  5. The way you articulate The thoughts is as refreshing as the first sip of coffee in the morning.

  6. Ryan Demore表示:

    Brilliant writing! You’ve perfectly captured the essence of the topic.

  7. I’m always excited to see The posts in my feed. Another excellent article!

  8. 비아그라 치매
    비아그라와 치매: 실제 연관성과 과학적 이해

  9. Laila Dirkse表示:

    The commitment to high quality content really shows. I’m always excited to read The work.

  10. Thank you for the hard work you put into this post. It’s much appreciated!

  11. I admire the way you tackled this hard to understand issue. Very enlightening!

  12. 비아그라 store – 고객문의
    24시간 실시간 상담 언제든지 문의 주세요!
    아래 양식을 작성하여 직접 문의해 주시기 바랍니다. 귀하의 의견과 제안은 언제나 감사드립니다.

  13. 비아그라 효능을 극대화하기 위한 팁
    비아그라 효능

  14. 베트남 비아그라 구매
    베트남에서 비아그라 구매 탐색: 여행자를 위한 가이드

  15. 비아그라 구입 병원
    병원에서의 비아그라: 환자에게 안전하고 효과적인가?

  16. Williambet表示:

    Скачать свежие новинки песен https://muzfo.net 2024 года ежедневно. Наслаждайтесь комфортным прослушиванием, скачивайте музыку за пару кликов на сайте.

  17. крейзи манки играть онлайн crazy-monkey-ru.ru .

  18. Incredibly informative post! I learned a lot and look forward to more.

  19. Thoughtful analysis that made me think, which is quite the feat these days.

  20. The writing is a masterpiece. You managed to cover every aspect with such finesse.

  21. The work is truly inspirational. I appreciate the depth you bring to The topics.

  22. sl2.top表示:

    Hello! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying
    to get my blog to rank for some targeted keywords but I’m not seeing very
    good success. If you know of any please share. Many thanks!
    You can read similar art here

  23. The Writing is like a favorite coffee shop where the drinks are always warm and the atmosphere is inviting.

  24. The creativity and insight left a big impression on me. Fantastic job!

  25. 비아그라 자주 먹으면
    정기적인 비아그라 섭취의 놀라운 건강상의 이점

  26. Reading The post was like going on a first date with my mind. Excited for the next rendezvous.

  27. 비아그라 효과 없는사람
    비아그라 효과가 없는 사람: 이유와 대안

發佈留言

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