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

26,705 Responses

  1. A neighbor of mine encouraged me to take a look at your blog site couple weeks ago, given that we both love similar stuff and I will need to say I am quite impressed.

  2. выведение из запоя на дому в екатеринбурге выведение из запоя на дому в екатеринбурге .

  3. Francismor表示:

    What this high school senior wants adults to know about classroom phone bans
    услуги медиатора стоимость
    юридическая помощь онлайн
    сбербанк политика конфиденциальности
    сберюрист личный
    юрист по кредитам консультация бесплатно онлайн
    кредит сбера для физических лиц
    консультация юристов онлайн
    юрист онлайн консультация
    ипотечный специалист сбербанк
    платные юридические консультации онлайн

    When my friends and I walked into homeroom on the first day of school this year, my teacher told all of us to put our phones in a black plastic box on an old desk by the classroom door.

    Handing over our phones during class is an official school policy, and my teachers always make this announcement at the beginning of the school year. But teachers would usually forget about the box by third period on the first day, never to be mentioned again by the second day of school. This year, however, the policy stuck that entire first day — and every day since.
    I asked my Latin teacher why the school was suddenly getting so strict on phones. It turns out that over the summer most of the teachers had read social psychologist Jonathan Haidt’s book “The Anxious Generation: How the Great Rewiring of Childhood Is Causing an Epidemic of Mental Illness.”

    Haidt, the Thomas Cooley Professor of Ehtical Leadership at New York University Stern School of Business, argues that a phone-based childhood leads to mentally unhealthy kids who are unprepared for life and, in my Latin teacher’s words, it “really freaked us out.” Teachers were serious about taking our phones now.

    It’s not just causing trouble at my school. Some 72% of public high school teachers in the United States say that cell phone distraction among their students is a major problem, according to a study published by the Pew Research Center in April. In high schools that already have cell phone policies, 60% of teachers say that the policies are very or somewhat difficult to enforce, the same study reported.

    Several states have passed laws attempting to restrict cell phone use in schools, and California Gov. Gavin Newsom recently signed legislation requiring school districts to regulate cell phone use. At least seven of the 20 largest school districts in the nation have either banned phones during the school day or plan to do so.

  4. SamuelCic表示:

    https://stromectol.agency/# purchase stromectol online

  5. Willian Alo表示:

    You must take part in a contest for probably the greatest blogs on the web. I will recommend this website!

  6. Danielser表示:

    The WNBA is having a real moment – Caitlin Clark and the league’s historic season by the numbers
    онлайн консультация юриста по семейным делам
    юридическая проверка квартиры при покупке сбербанк отзывы
    сбербанк согласие на обработку персональных данных
    юридическая консультация семейное право
    семейный адвокат консультации
    консультация семейного адвоката
    юрист по недвижимости в москве консультация
    юрист по семейному праву консультация бесплатно москва
    сбербанк по обслуживанию юридических лиц
    юрист по недвижимости

    When many of us hear the “Fall Classic,” we automatically think of baseball’s World Series. I’m not sure that will be the case for future generations.

    Yes, I’m being somewhat provocative with that line, but the WNBA Finals have arrived on the heels of what can only be described as a historic season for the league. Across a metric of statistics, it’s clear that America’s interest in the WNBA is at the highest point this century in large part because of Indiana Fever star Caitlin Clark.

    Let’s start simple: Google searches. They’ve been higher this WNBA season, starting with the draft in April, than at any point since we’ve had data (2004). Searches for the WNBA are up over 300% compared to last season, up over 850% compared to five seasons ago, and have risen nearly 1,400% from a decade ago.

    That is, the WNBA has been rising, and this year it really took off.
    This interest has translated into revenue for the league. Attendance is up a staggering 48% from 2023. There wasn’t a single team with an average regular season home attendance of five figures (10,000+) in 2023. This season, there were six.

    Leading the charge was Clark’s Fever. A little more than 4,000 people attended their average game in 2023, which ranked them second to last. This season, more than 17,000 did, a 319% rise that put them far and away ahead of any other WNBA team and ahead of five NBA teams, including the hometown Indiana Pacers.

    We see the same pattern in merchandise. Sales are up 600% from last year. This includes the boost from rookie sensations Clark, who had the best-selling jersey, and Angel Reese of the Chicago Sky, who had the second-best-selling jersey.

  7. SamuelCic表示:

    https://amoxil.llc/# where can you get amoxicillin

  8. Quite the opposite, product innovations themselves usually function course of innovations, such that the answer only worsens the initial drawback.25 When the car and client durables industries began to throw off capital and labour within the 1960s and 70s, new lines like microelectronics weren’t able to absorb the excess, even a long time later.

  9. NicolasLoole表示:

    https://stromectol.agency/# ivermectin 50 mg

  10. Vogue NL was launched in 2012 as Vogue Nederland.

  11. In For a brand new Liberty: The Libertarian Manifesto, Rothbard proposes a once-and-for-all escape from the 2 major political parties, the ideologies they embrace, and their central plans for using state power against folks.

  12. Stevenjaw表示:

    https://zithromax.company/# buy zithromax without presc
    buy zithromax online fast shipping

  13. NicolasLoole表示:

    https://semaglutide.win/# rybelsus price

  14. принудительный вывод из запоя краснодар принудительный вывод из запоя краснодар .

  15. Matthewweind表示:

    stromectol how much it cost: stromectol price – ivermectin 3mg tablets

  16. ixxx_lsMn表示:

    xxxfree porn videos ixxxsexvideo.com .

  17. Matthewweind表示:

    neurontin 100mg: order gabapentin – neurontin 100mg cost

  18. Michaelgax表示:

    amoxicillin 500mg capsule buy online amoxil best price amoxicillin online no prescription

  19. The underwriting profit comes from our direct relationship building with the borrower.

  20. Fashion Your Space with Sculptures and Residence Decor Accents.

  21. Michaelgax表示:

    zithromax 500mg buy zithromax z-pak online zithromax online pharmacy canada

  22. Used merchandise cannot be returned until defective.

  23. Whether you’re using your shotgun for home defense or another buy, it is necessary to carefully consider which ammo you employ.

  24. This can allow you to plan your storage beforehand.

  25. Along with a sofa and some chairs, move in oversize floor pillows for lounging.

  26. The closet has sufficient storage to prepare clothes and daily items, but it isn’t large sufficient to crowd the flooring house.

  27. Unquestionably, these Ladies Celebration Shoes with Heels are certified type icons.

  28. Earlier than the saws buzz and the mud flies, specify one room as your headquarters.

發佈留言

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