踩到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,063 Responses

  1. Williecrady表示:

    Slot menawarkan berbagai jenis permainan bonus https://preman69.tech/# Slot menawarkan kesenangan yang mudah diakses

  2. Williecrady表示:

    Kasino di Indonesia menyediakan hiburan yang beragam https://preman69.tech/# Kasino di Bali menarik banyak pengunjung

  3. ThomasThype表示:

    Kasino di Bali menarik banyak pengunjung: slot88 – slot88

  4. Williecrady表示:

    Banyak kasino memiliki promosi untuk slot https://slot88.company/# Slot dengan tema film terkenal menarik banyak perhatian

  5. ThomasThype表示:

    Pemain harus menetapkan batas saat bermain: slot demo – slotdemo

  6. DavidCooth表示:

    https://preman69.tech/# Bermain slot bisa menjadi pengalaman sosial

  7. Williecrady表示:

    Beberapa kasino memiliki area khusus untuk slot https://preman69.tech/# Kasino sering memberikan hadiah untuk pemain setia

  8. DavidCooth表示:

    https://garuda888.top/# Slot klasik tetap menjadi favorit banyak orang

  9. ThomasThype表示:

    Kasino sering mengadakan turnamen slot menarik: garuda888 slot – garuda888

  10. Aaronbus表示:

    bonaslot bonaslot Slot menawarkan kesenangan yang mudah diakses

  11. ThomasThype表示:

    Permainan slot bisa dimainkan dengan berbagai taruhan: bonaslot.site – bonaslot.site

  12. Williecrady表示:

    Keseruan bermain slot selalu menggoda para pemain https://garuda888.top/# Mesin slot baru selalu menarik minat

  13. Williecrady表示:

    Pemain sering mencoba berbagai jenis slot http://slot88.company/# Jackpot progresif menarik banyak pemain

  14. Aaronbus表示:

    garuda888 slot garuda888 slot Slot menjadi bagian penting dari industri kasino

  15. DavidCooth表示:

    https://garuda888.top/# Slot menawarkan berbagai jenis permainan bonus

  16. Dannybrelm表示:

    лучшие подборки фильмов фильмы hdrezka 1080p

  17. srochno-zaym表示:

    Каталог финансовых организаций srochno-zaym-online.ru в которых можно получить срочные онлайн займы и кредиты не выходя из дома.

  18. Williecrady表示:

    Banyak kasino memiliki program loyalitas untuk pemain https://bonaslot.site/# Pemain sering berbagi tips untuk menang

  19. ThomasThype表示:

    Kasino selalu memperbarui mesin slotnya: preman69.tech – preman69 slot

  20. Williecrady表示:

    Banyak kasino memiliki promosi untuk slot https://preman69.tech/# Slot menjadi daya tarik utama di kasino

  21. Michaelnen表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken сайт
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  22. ThomasThype表示:

    Kasino menyediakan layanan pelanggan yang baik: garuda888 slot – garuda888.top

  23. DavidCooth表示:

    http://slot88.company/# Permainan slot mudah dipahami dan menyenangkan

  24. Aaronbus表示:

    slot 88 slot88.company Slot dengan fitur interaktif semakin banyak tersedia

  25. Haroldsinty表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  26. EugeneLot表示:

    Lucky Jet – твой шанс на большие выигрыши!
    Попробуй захватывающую краш-игру прямо сейчас! Регистрируйся и получи бонус до 500% на первый депозит с промокодом: LuckyJetTeam.
    сигналы лаки джет
    Об игре
    Lucky Jet — это не просто игра, а захватывающее приключение, в котором каждый момент может стать решающим! Эта краш-игра бросает вызов вашим инстинктам и способности быстро принимать решения. В основе игры — динамичная механика, где игроки ставят на рост коэффициента, но задача не в том, чтобы ждать до последнего, а вовремя вывести свой выигрыш, прежде чем персонаж взлетит слишком высоко и случится крах.

    Чем выше коэффициент, тем более значительная награда! Но не забывайте: в этом азартном путешествии важен каждый момент, ведь именно ваше решение о выводе решит, насколько велик будет ваш выигрыш. Это не просто игра, а настоящее испытание на скорость и удачу! Простые правила, быстрые раунды и реальные выигрыши – вот почему игроки выбирают Lucky Jet.

    Бонусы и промокоды в Lucky Jet
    В Lucky Jet вас ждут щедрые бонусы и эксклюзивные промокоды, которые помогут увеличить ваш баланс и продлить удовольствие от игры! Мы ценим активных игроков и регулярно запускаем новые акции, чтобы сделать ваш игровой процесс еще выгоднее.

    Актуальные бонусные предложения
    Бонус 500% на первый депозит
    Используйте промокод LuckyJetTeam при пополнении счета и получите увеличение депозита в 5 раз! Это отличная возможность начать игру с солидным запасом.
    Еженедельные акции и фриспины
    Чем больше вы играете, тем больше подарков получаете! Участвуйте в регулярных промо-акциях и получайте фриспины, бонусные деньги и дополнительные награды за активность.
    Кэшбэк до 10%
    Проиграли? Не беда! В Lucky Jet вы можете вернуть часть потерянных средств благодаря системе кэшбэка. Еженедельно вам будет начисляться до 10% возврата от проигранных ставок.
    Следите за новыми акциями! Мы постоянно обновляем бонусные предложения, поэтому не упустите возможность воспользоваться самыми выгодными промо. Подписывайтесь на новости и следите за актуальными акциями, чтобы всегда быть в выигрыше!

    Используйте бонусы и повышайте свои шансы на победу в Lucky Jet!

    Как начать играть в Lucky Jet
    Готовы испытать удачу и выиграть по-крупному? Следуйте этим простым шагам:

    Зарегистрируйтесь на официальном сайте 1win. Процесс регистрации занимает всего пару минут.
    Пополните счет удобным для вас способом: банковской картой, электронными кошельками или даже криптовалютой.
    Откройте Lucky Jet в разделе казино и приготовьтесь к динамичному игровому процессу.
    Сделайте ставку и следите за ростом коэффициента. Чем выше он поднимается – тем больше ваш потенциальный выигрыш.
    Выведите выигрыш до того, как Lucky Jet взлетит! Главное – не жадничать и вовремя остановиться, иначе ставка сгорит.
    Используйте стратегии, анализируйте предыдущие раунды и комбинируйте ставки, чтобы увеличить свои шансы на победу!

  27. Michaelnen表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken shop
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  28. DerekMax表示:

    check over here https://brd-wallet.com

  29. DavidCooth表示:

    https://preman69.tech/# Banyak kasino memiliki program loyalitas untuk pemain

發佈留言

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