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

10,350 Responses

  1. Definitely believe that which you said. Your favorite reason seemed to be on the net the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they just don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  2. JasonHes表示:

    This city is developing the world’s tallest timber tower, again
    работа в сфере досуга
    The US city of Milwaukee is already home to the world’s tallest timber tower. But another, even taller, wooden skyscraper could be added to its skyline, designed by Vancouver-based studio Michael Green Architects (MGA).

    The firm recently released plans for the development, which includes a 55-story tower made principally from mass timber — thick, compressed, multilayered panels of solid wood. If built, it would usurp the current world title holder, the 25-story Ascent tower by Korb + Associates Architects, as well as becoming the tallest building in the state of Wisconsin.

    MGA, which specializes in wooden architecture, hopes that the project will set a “new global benchmark for mass timber construction.”

    The project is part of the redevelopment of the Marcus Performing Arts Center, which opened in 1969 and won the Honor Award for Excellence in Architectural Design from the American Institute of Architects in 1970. Led by Neutral, which bills itself as a “regenerative development company,” the redesign will transform what is currently the center’s concrete parking lot into a space with residential units, offices, restaurants, cafes, grocery stores and public plazas. According to MGA, construction will cost an estimated $700 million. The plan is currently going through the city’s approval process, during which it is expected to evolve.

    Why timber?
    While the use of mass timber is steadily increasing worldwide, thanks to changes in building regulations and shifting attitudes towards the material, it has yet to match the sheer height of buildings made of concrete and steel — although a slew of timber high-rises have been proposed in recent years. MGA says its tower design would be approximately 600 feet (182 meters) tall — more than double the 284 feet (87 meter) tall Ascent tower.

    “The race for height is important,” said Michael Green, an architect and founder of MGA. “It’s not about showing off, it’s about showing what’s possible to the public.”

    He argued that the reason timber skyscrapers haven’t yet become mainstream is because climate change hasn’t been at the center of the conversation. “We didn’t really need to challenge the status quo of steel and concrete,” he said. “But because those materials are so hard on the climate, we had to find a different way to build towers and big buildings in general.”

  3. What an eye-opening and meticulously-researched article! The author’s attention to detail and capability to present complicated ideas in a understandable manner is truly commendable. I’m extremely enthralled by the depth of knowledge showcased in this piece. Thank you, author, for sharing your wisdom with us. This article has been a game-changer!

  4. i9bet表示:

    I just sent this post to a bunch of my friends as I agree with most of what you’re saying here and the way you’ve presented it is awesome.

  5. Red88表示:

    I had highly recommend this blog to my good friend, it’s so good

  6. Sazrsyp表示:

    Здравствуйте!
    Заказать документ о получении высшего образования
    posode.ru/search

  7. Uazrxlp表示:

    Привет,друзья!
    Приобрести диплом университета .
    telegra.ph/kupit-medicinskij-diplom-s-zaneseniem-v-reestr-08-13-4

  8. biardiova表示:

    A retrospective study analyzing the costs and incidence of emergency department visits related to ADRs in patients 65 years of age or older identified the following risk factors 10 priligy dapoxetine amazon

  9. Ndrogz表示:

    order voltaren 100mg online – buy generic aspirin brand aspirin

  10. Davidged表示:

    CV

  11. GermanAxowl表示:


    Строительство, ремон своими руками. Советы мастеров и лучших специалстов в своем деле.

    Каким вы видите свой будущий дом? Выполненный в духе уютного загородного шале или со сложными геометрическими формами и яркими элементами?

    <a href=https://www.vuz-chursin.ru/stroitelstvo]Строительство

    <a href=https://www.vuz-chursin.ru/stroymaterialy-0]Стройматериалы

    <a href=https://www.vuz-chursin.ru/remont-i-otdelka]Отделка
    Для большинства людей своя, пускай, даже крохотная, но отдельная однокомнатная квартира, намного слаще, чем аренда 5-комнтантного пентхауса за смешные деньги. Здесь можно устанавливать свои правила, планировать ремонт, делать перестановку, а единственное ограничение – это пространство.

    Каталог полезных статей о стройке и ремонте <a href=https://vuz-chursin.ru/.

  12. Blainelow表示:

    Если вы хотите купить Озепмпик в Москве, обратите внимание на аптеки, предлагающие этот препарат с доставкой. Озепмпик — это современное средство, которое помогает контролировать уровень глюкозы и снижать вес. Узнайте цены на Озепмпик и выберите удобный способ приобретения. https://t.me/ozempik_kupit11

  13. Samuelalush表示:

    Уборка запущенной квартиры в Москве https://uborka-zapushchennyh-kvartir.ru/

  14. WilliamDeeli表示:

    Добрый день!
    Мы предлагаем дипломы.
    birzha-othodov.ru/club/user/22923/blog/6183

  15. Eanrbxa表示:

    Привет!
    Мы можем предложить дипломы любой профессии по приятным тарифам.
    onlineboxing.net/jforum/user/profile/287687.page

  16. custom tees表示:

    I am glad to be a visitor on this website!, regards for this rare information!

  17. Nevertheless, it’s all carried out with tongues rooted solidly in cheeks, and everybody has got nothing but absolutely love for their friendly neighborhood scapegoat. In reality, he is not merely a pushover. He is simply that extraordinary breed of person solid enough to take all that good natured ribbing for what it really is.

  18. Not solely are you stocking up and saving money, but you will have fewer panicked trips to the store, too.

  19. silovye_tbSn表示:

    Топовые силовые тренажеры Impulse Fitness, для эффективных тренировок.
    Удивительные тренажеры Impulse Fitness, которые изменят ваше представление о тренировках.
    Советы по покупке тренажеров Impulse Fitness, для эффективной тренировки.
    Тренируйтесь с удовольствием: лучшие силовые тренажеры Impulse Fitness, и поднять настроение.
    Новейшие силовые тренажеры Impulse Fitness, для требовательных спортсменов.
    Прогрессивные силовые тренажеры Impulse Fitness, для тренировок высокого уровня.
    Инновации в мире спорта: тренажеры Impulse Fitness, для современных тренировок.
    Эффективные тренировки с тренажерами Impulse Fitness, и улучшения физической формы.
    Как достичь идеальной формы с помощью силовых тренажеров Impulse Fitness, для оптимальных результатов.
    Тренировочные тренажеры Impulse Fitness для дома, для удобных тренировок дома.
    купить профессиональные силовые тренажеры https://trenazhery-impulse-fitness.ks.ua/ .

  20. Samuelalusy表示:

    Как же можно так жестоко поступать с людьми! Я всегда верил в кооператив “Бест Вей“, потому что знал, что там работают честные и порядочные люди. Я вложил свои деньги с уверенностью, что они в надежных руках. И теперь нас обвиняют в мошенничестве! Да это просто какой-то кошмар! Эти “потерпевшие”, которые якобы пострадали, – на самом деле просто аферисты, которые хотят нажиться на этом процессе. У них нет никаких доказательств, никаких договоров, никаких подтверждений. А наши счета арестованы, и мы не можем получить свои деньги – за что? За что нам такие страдания? Я не понимаю, как так можно, но я не сдамся! Я буду бороться за свои права, за свою честь и за справедливость! И я верю, что правда восторжествует, и все эти лгуны и мошенники будут наказаны!

  21. This led to CCS changing into the only viable resolution to overcome this political conflict.

  22. The 610 Loop opened within the 1960s.

  23. French, Jordan (2 April 2018).

  24. 亀田 弱い表示:

    To start any home primarily based business you only have to have an internet connection.

發佈留言

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