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

28,621 Responses

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

  2. Robertnen表示:

    ЖК Резиденция лайф ЖК Космос ЖК Крылья – это строит недобросовестный застройщик – Паритет Девелопмент ИНН 7203567694 Не рекомендую покупать квартиры. Будите обмануты @dontcheatpeople – телеграмм.

  3. Тут делают продвижение комплексное продвижение медицинских сайтов seo. медицинских. сайтов

  4. Сервисный центр предлагает срочный ремонт видеокарты axle ремонт видеокарты axle на дому

  5. WilliamTut表示:

    Comet likely last seen when Neanderthals walked Earth could soon dazzle in the night sky
    Смартфон Samsung Galaxy S24 Ultra SM-S9280 12GB/512GB титановый черный купить недорого
    A recently discovered comet, known as C/2023 A3 Tsuchinshan–ATLAS, will make its closest approach of Earth on Saturday. Sky-gazers won’t want to miss the event since it may be the last time the comet will be seen in the night sky for another 80,000 years.

    The comet successfully reached perihelion, its closest point to the sun in its orbital path around the parent star, on September 27, and was visible for those in the Southern Hemisphere in September and early October. Now, the icy body is on its way out of the inner solar system and will be visible to those in the Northern Hemisphere in mid-October through early November, according to NASA.

    On Saturday, the comet will come within about 44 million miles (nearly 71 million kilometers) of Earth. The comet is making its first documented flyby of our planet, according to NASA. With its 80,000-year orbit, the celestial body would have been last seen from Earth at the time of the Neanderthals.
    Those looking to catch a glimpse of the once-in-a-lifetime event will want to look in the western part of the night sky, shortly after sunset, according to EarthSky.

    The comet will look like a bright fireball in the dark sky with a long, extended tail. Bill Cooke, lead of NASA’s Meteoroid Environment Office at the Marshall Space Flight Center in Huntsville, Alabama, recommends a pair of binoculars for enhanced viewing of the comet.

    “It’s not going to zing across the sky like a meteor. It will just appear to hang there, and it will slowly change position from night to night,” Cooke said. “If you can see (the comet) with your unaided eye, (using) the binoculars will knock your socks off.”

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

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

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

  8. Stephenideox表示:

    https://prestigeagency.org/ – party girls в Дубаи

  9. Stevenjaw表示:

    https://gabapentin.auction/# neurontin generic
    zithromax azithromycin

  10. Michaelgax表示:

    over the counter amoxicillin amoxil best price amoxicillin without a doctors prescription

  11. https://prestigeagency.org/ – вакансии хостес

  12. ThomasceS表示:

    https://prestigeagency.org/ – вакансии хостес

  13. Тут делают продвижение разработка сайта медицинской клиники создать сайт медицинского центра

  14. Michaelgax表示:

    buy zithromax online cheap generic zithromax zithromax 250

  15. Matthewweind表示:

    zithromax online usa: buy zithromax z-pak online – zithromax 500 mg for sale

  16. Сервисный центр предлагает ремонт телефона vsmart на дому ремонт телефона vsmart

  17. Matthewweind表示:

    cost of neurontin: order gabapentin – neurontin 600

  18. магазин сейфов предлагает сейф 3 класс в москве купить сейф 3 класс

  19. Тут делают продвижение продвижение клиники стратегия с роботами

  20. NicolasLoole表示:

    https://zithromax.company/# generic zithromax over the counter

  21. работа в астане после 19 00 работа в астане после 19 00 .

  22. Stevenjaw表示:

    http://amoxil.llc/# amoxicillin tablets in india
    zithromax capsules australia

  23. Michaelgax表示:

    neurontin 100mg price buy neurontin online uk neurontin tablets no script

發佈回覆給「Brycejam」的留言 取消回覆

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