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

  1. Rogerinhaw表示:

    Siham Haleem, a private tour guide for 15 years, says that Doha now has many world-class, modern museums — the National Museum of Qatar being a firm personal favorite. And yet he says that visiting Sheikh Faisal’s museum should still be on everybody’s to-do list.
    simpleswap
    “For those eager to learn about Qatar’s — and the region’s — heritage and beyond, the museum is an ideal destination,” he says. “Personally, I’m captivated by the car collection, the fossils, and especially the Syrian house, painstakingly transported and reassembled piece by piece.”

    Stephanie Y. Martinez, a Mexican-American student mobility manager at Texas A&M University in Qatar likes the museum so much she includes it on all of her itineraries for students visiting from the main campus in Texas.

    “The guided tours are very detailed, and the collections found at the museum have great variety and so many stories to unfold,” she says. “Truly, the museum has something to pique everyone’s interest. My favorites are the cars and the furniture exhibits showcasing wood and mother-of-pearl details. Definitely one of my favorite museums in Qatar, every time I visit I learn something new.”

    Raynor Abreu, from India, also had praise for the unusual and immense collection.

    “Each item has its own story, making the visit even more interesting,” he says. “It’s also impressive to know that Sheikh Faisal started collecting these unique pieces when he was very young. Knowing this makes the museum even more special, as it reflects his lifelong passion for history and culture.”

    It takes time and dedication to truly examine the many collections within the museum — especially since most of them are simply on display without explanation.

    Eclectic it may be, but it’s hard to fault the determination of Sheikh Faisal, who has brought together items that tell the story of Qatar and the Middle East.

    Sarah Bayley, from the UK, says she visited the museum recently with her family, including 16 and 19-year-old teenagers, and was won over by its sheer eccentricity.

    “Amazing. Loved it. It is a crazy place.”

  2. RodgerJat表示:

    Remote and rugged
    eigenlayer
    A more organic way to see this coast is by the multi-day coastal ferry, the long-running Sarfaq Ittuk, of the Arctic Umiaq Line. It’s less corporate than the modern cruise ships and travelers get to meet Inuit commuters. Greenland is pricey. Lettuce in a local community store might cost $10, but this coastal voyage won’t break the bank.

    The hot ticket currently for exploring Greenland’s wilder side is to head to the east coast facing Europe. It’s raw and sees far fewer tourists, with a harshly dramatic coastline of fjords where icebergs drift south. There are no roads and the scattered population of just over 3,500 people inhabit a coastline roughly the distance from New York to Denver.

    A growing number of small expedition vessels probe this remote coast for its frosted scenery and wildlife. Increasingly popular is the world’s largest fjord system of Scoresby Sound with its sharp-fanged mountains and hanging valleys choked by glaciers. Sailing north is the prosaically named North East Greenland National Park, fabulous for spotting wildlife on the tundra.

    Travelers come to see polar bears which, during the northern hemisphere’s summer, move closer to land as the sea-ice melts. There are also musk oxen, great flocks of migrating geese, Arctic foxes and walrus.
    Some of these animals are fair game for the local communities. Perhaps Greenland’s most interesting cultural visit is to a village that will take longer to learn how to pronounce than actually walk around — Ittoqqortoormiit. Five hundred miles north of its neighboring settlement, the 345 locals are frozen in for nine months of the year. Ships sail in to meet them during the brief summer melt between June and August.

    Locked in by ice, they’ve retained traditional habits.

    “My parents hunt nearly all their food,” said Mette Barselajsen, who owns Ittoqqortoormiit’s only guesthouse. “They prefer the old ways, burying it in the ground to ferment and preserve it. Just one muskox can bring 440 pounds of meat.”

  3. Chesterwib表示:

    Curiosity has maintained pristine pieces of the Cumberland sample in a “doggy bag” so that the team could have the rover revisit it later, even miles away from the site where it was collected. The team developed and tested innovative methods in its lab on Earth before sending messages to the rover to try experiments on the sample.
    changelly exchange
    In a quest to see whether amino acids, the building blocks of proteins, existed in the sample, the team instructed the rover to heat up the sample twice within SAM’s oven. When it measured the mass of the molecules released during heating, there weren’t any amino acids, but they found something entirely unexpected.

    An intriguing detection
    The team was surprised to detect small amounts of decane, undecane and dodecane, so it had to conduct a reverse experiment on Earth to determine whether these organic compounds were the remnants of the fatty acids undecanoic acid, dodecanoic acid and tridecanoic acid, respectively.

    The scientists mixed undecanoic acid into a clay similar to what exists on Mars and heated it up in a way that mimicked conditions within SAM’s oven. The undecanoic acid released decane, just like what Curiosity detected.

    Each fatty acid remnant detected by Curiosity was made with a long chain of 11 to 13 carbon atoms. Previous molecules detected on Mars were smaller, meaning their atomic weight was less than the molecules found in the new study, and simpler.
    “It’s notable that non-biological processes typically make shorter fatty acids, with less than 12 carbons,” said study coauthor Dr. Amy Williams, associate professor of geology at the University of Florida and assistant director of the Astraeus Space Institute, in an email. “Larger and more complex molecules are likely what are required for an origin of life, if it ever occurred on Mars.”

  4. Derekgroum表示:

    apotek online recept: Apotek hemleverans idag – Apoteket online

  5. Michaeltor表示:

    Kamagra kaufen ohne Rezept: Kamagra Oral Jelly kaufen – Kamagra Oral Jelly kaufen

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

  7. HomerFaw表示:

    https://apotekonlinerecept.com/# Apotek hemleverans recept

  8. Derekgroum表示:

    de online drogist kortingscode: Apotheek online bestellen – Apotheek Max

  9. HomerFaw表示:

    https://apotheekmax.com/# Beste online drogist

  10. KevinInalm表示:

    Why there’s a huge collection of vintage cars stored in the middle of the desert
    base bridge
    Back at the turn of the 21st century, Qatar was a country with few cultural attractions to keep visitors and residents entertained. Yet the Sheikh Faisal Bin Qassim Al Thani Museum — known as the FBQ Museum — was a place that most people visited as an alternative to the then-still rather ramshackle National Museum of Qatar.

    You had to make an appointment, and drive out into the desert, getting lost a few times along the way, but then you were welcomed to the lush Al Samriya Farm with a cup of tea and some cake. The highlight was being allowed into a space crammed full with shelves and vitrines holding all sorts of eclectic artifacts from swords to coins — with the odd car and carriage standing in the grounds.

    It wasn’t necessarily the kind of museum you’d find elsewhere in the world, but it was definitely a sight that needed seeing.

    Today, it has grown and now claims to be one of the world’s largest private museums. It holds over 30,000 items, including a fleet of traditional dhow sailboats, and countless carpets. There’s also an entire house that once stood in Damascus, Syria.

    There are archaeological finds dating to the Jurassic age, ancient copies of the Quran, a section that details the importance of pearling within Qatar’s history, and jewelry dating to the 17th century.

    There are also items from 2022’s FIFA World Cup in Qatar including replica trophies, balls used in the games, entry passes, football jerseys and even shelves full of slightly creepy dolls and children’s plush animals.

    Some of the more disturbing exhibits include various items of Third Reich paraphernalia in the wartime room, and, strangely enough, several showcases of birds’ legs with marking rings on them. Basically, whatever you can think of, you have a very good chance of finding it here.

    Rumor even has it that behind a locked door is a room filled with the late Princess Diana’s dresses and other memorabilia, accessible only to a select few visitors. Another door hides a room, no longer open to the public, filled with collectibles of the late Saddam Hussein.

  11. Johnniebax表示:

    Curiosity rover makes ‘arguably the most exciting organic detection to date on Mars’
    bungee exchange

    The NASA Curiosity rover has detected the largest organic molecules found to date on Mars, opening a window into the red planet’s past. The newly detected compounds suggest complex organic chemistry may have occurred in the planet’s past — the kind necessary for the origin of life, according to new research.

    The organic compounds, which include decane, undecane and dodecane, came to light after the rover analyzed a pulverized 3.7 billion-year-old rock sample using its onboard mini lab called SAM, short for Sample Analysis at Mars.

    Scientists believe the long chains of molecules could be fragments of fatty acids, which are organic molecules that are chemical building blocks of life on Earth and help form cell membranes. But such compounds can also be formed without the presence of life, created when water interacts with minerals in hydrothermal vents.

    The molecules cannot currently be confirmed as evidence of past life on the red planet, but they add to the growing list of compounds that robotic explorers have discovered on Mars in recent years. A study detailing the findings was published Monday in the journal Proceedings of the National Academy of Sciences.
    The detection of the fragile molecules also encourages astrobiologists that if any biosignatures, or past signs of life, ever existed on Mars, they are likely still detectable despite the harsh solar radiation that has bombarded the planet for tens of millions of years.

    “Ancient life, if it happened on Mars, it would have released some complex and fragile molecules,” said lead study author Dr. Caroline Freissinet, research scientist at the French National Centre for Scientific Research in the Laboratory for Atmospheres, Observations, and Space in Guyancourt, France. “And because now we know that Mars can preserve these complex and fragile molecules, it means that we could detect ancient life on Mars.”

  12. Leonardmooli表示:

    Everyone is talking about Greenland. Here’s what it’s like to visit
    cow swap

    A few months ago, Greenland was quietly getting on with winter, as the territory slid deeper into the darkness that envelops the world’s northerly reaches at this time of year.

    But President Donald Trump’s musings about America taking over this island of 56,000 largely Inuit people, halfway between New York and Moscow, has seen Greenland shaken from its frozen Arctic anonymity.

    Denmark, for whom Greenland is an autonomous crown dependency, has protested it’s not for sale. Officials in Greenland, meanwhile, have sought to assert the territory’s right to independence.

    The conversation continues to intensify. A contentious March 28 visit to a US military installation by Usha Vance, the second lady, accompanied by her husband, Vice President JD Vance, was the latest in a series of events to focus attention on Trump’s ambitions for Greenland.

    The visit was originally planned as a cultural exchange, but was shortened following complaints from Greenland Prime Minister Mute B. Egede.

    Had the Vances prolonged their scheduled brief visit, they would’ve discovered a ruggedly pristine wildernesses steeped in rich Indigenous culture.

    An inhospitable icecap several miles deep covers 80% of Greenland, forcing the Inuit to dwell along the shorelines in brightly painted communities. Here, they spend brutally cold winters hunting seals on ice under the northern lights in near perpetual darkness. Although these days, they can also rely on community stores.

    The problem for travelers over the years has been getting to Greenland via time-consuming indirect flights. That’s changing. Late in 2024, the capital Nuuk opened a long-delayed international airport. From June 2025, United Airlines will be operating a twice-weekly direct service from Newark to Nuuk.

    Two further international airports are due to open by 2026 — Qaqortoq in South Greenland and more significantly in Ilulissat, the island’s only real tourism hotspot.

  13. Michaeltor表示:

    Kamagra kaufen: Kamagra Oral Jelly – Kamagra kaufen ohne Rezept

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

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

  16. Malcolmseern表示:

    Kamagra online bestellen Kamagra Gel Kamagra Oral Jelly

發佈留言

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