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

  1. Hello, I think your site might be having browser compatibility issues. When I look at your blog site in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!

  2. LED lamps used in theaters, photography, news-gathering (TV broadcasts, film, similar) and even lighting used in nightclubs on the dance floor and in operation rooms (surgery) are considered in the General Lighting application.

  3. Most money exchangers in Hyderabad manipulate the customer’s logic by using phrases like “Daily Rates” and succeed in making a fool out of the customer.

  4. Stephenzek表示:

    https://furosemide.win/# lasix furosemide 40 mg

  5. whoah this weblog is fantastic i really like reading your articles. Keep up the great paintings! You know, many individuals are looking round for this info, you can help them greatly.

  6. DanielTet表示:

    Cytotec 200mcg price https://lipitor.guru/# can you buy lipitor over the counter
    lasix generic name

  7. Jamesric表示:

    lipitor 20 mg pill: buy atorvastatin online – lipitor 20mg price australia

  8. Richardsudge表示:

    The man turning jet planes into cool houses
    анальный секс смотреть
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  9. Hey there, You have performed a great job. I?ll definitely digg it and individually recommend to my friends. I am sure they will be benefited from this site.

  10. Stanleyinolf表示:

    cytotec buy online usa buy cytotec online п»їcytotec pills online

  11. Trefhgd表示:

    Привет!
    Можно ли быстро купить диплом старого образца и в чем подвох?
    flowerwheel.synology.me/dokuwiki/doku.php?id=gosznacdiplom
    Поможем вам всегда!.

  12. JoshuaDen表示:

    The man turning jet planes into cool houses
    анальный секс можно
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  13. Frankguara表示:

    The man turning jet planes into cool houses
    мальчик гей
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  14. Fzsxvt表示:

    order neurontin 100mg online cheap – buy azulfidine medication sulfasalazine 500 mg tablet

  15. JustinBreve表示:

    комплексное seo продвижение https://process-seo.ru

  16. Sunwin表示:

    Hi my family member! I want to say that this article is amazing, great written and include approximately all important infos. I’d like to see more posts like this .

  17. Thanks for the auspicious writeup. It in reality used to be a entertainment account it. Look complicated to far delivered agreeable from you! By the way, how can we communicate?

  18. I just added this website to my rss reader, great stuff. Cannot get enough!

  19. JustinBreve表示:

    сколько стоит seo оптимизация сайта https://process-seo.ru

  20. Lariorgqq表示:

    Официальная покупка диплома вуза с упрощенной программой обучения
    telegra.ph/gde-kupit-chistyj-diplom-08-13-4

  21. Lariorfjf表示:

    Как безопасно купить диплом колледжа или ПТУ в России, что важно знать
    telegra.ph/kupit-diplom-uchilishcha-v-novosibirske-08-13-10

  22. WilliamDeeli表示:

    Привет!
    Мы изготавливаем дипломы.
    svae.by/blog.php?cp=10022

  23. DanielTet表示:

    cytotec buy online usa http://lisinopril.guru/# lisinopril 10 mg
    lasix for sale

  24. Stephenzek表示:

    http://tamoxifen.bid/# tamoxifen cost

  25. I would like to thank you for the efforts you’ve put in writing this site. I’m hoping the same high-grade site post from you in the upcoming also. In fact your creative writing abilities has inspired me to get my own web site now. Actually the blogging is spreading its wings quickly. Your write up is a great example of it.

  26. Diplomi_hmEa表示:

    Привет!
    Заказать документ ВУЗа можно в нашей компании в Москве.
    djwx.com/forums/user/profile/65065.page

  27. DanielPum表示:

    Роман Василенко – человек, который добился всего своим трудом и талантом. К сожалению, в мире всегда найдутся те, кто завидует чужому успеху и пытается оклеветать честное имя. СМИ часто прибегают к недостоверным фактам и ложным обвинениям, чтобы привлечь внимание к своим публикациям. Романа не раз пытались очернить, но те, кто его знает, понимают, что это всего лишь попытки недоброжелателей. Его репутация остается непоколебимой, потому что он всегда действует честно и открыто. Его проект «Бест Вей» стал единственным шансом для многих россиян приобрести жилье, особенно в регионах, где молодежь часто вынуждена уезжать в поисках лучшей жизни. Роман продолжает идти вперед, строя успешный и честный бизнес, несмотря на все преграды.

  28. Williebak表示:

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

  29. Mazrvvq表示:

    Привет!
    Полезные советы по безопасной покупке диплома о высшем образовании
    rf-4fun.ru/index.php?/topic/1865-нерф-кор/#comment-3554

發佈留言

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