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

17,347 Responses

  1. BrettTIT表示:

    ed meds by mail: cheap cialis – low cost ed meds online

  2. BrettTIT表示:

    ed medicine online: cheap cialis – online ed treatments

  3. Barrybib表示:

    Buy Cialis online: Max Pills For Men – Generic Cialis without a doctor prescription

  4. kubet表示:

    nicee content keep writing

  5. Lovely just what I was looking for. Thanks to the author for taking his clock time on this one.

  6. CharlesPem表示:

    Смартфоны. Читайте последние новости на тему в ленте новостей на сайте formobile.top
    новости смартфонов

  7. JimmyGully表示:

    Discover Stargate Finance: Your Gateway to DeFi
    In the rapidly evolving world of decentralized finance (DeFi), Stargate Finance stands out as a reliable platform for decentralized transactions and yield optimization. Let’s explore how Stargate Finance can enhance your financial strategies.
    stargate finance
    Why Choose Stargate Finance?
    Stargate Finance offers a comprehensive suite of tools designed to facilitate seamless and secure transactions. Here’s why you should consider integrating Stargate Finance into your DeFi experience:

    Seamless Cross-Chain Transactions: Facilitate instant and smooth transactions across multiple blockchain networks without the hassle of traditional exchanges.
    High-Performance Liquidity Pools: Access a wide range of liquidity pools to optimize your yield farming strategies and maximize returns.
    Secure Protocols: Enjoy peace of mind with top-tier security measures designed to protect your assets and data.
    Features that Enhance Your DeFi Experience
    Stargate Finance uniquely positions itself by offering features that cater to both novice and veteran DeFi users:

    Intuitive User Interface: Navigate effortlessly through the platform with a user-friendly interface that simplifies complex DeFi operations.
    24/7 Customer Support: Get assistance anytime with a dedicated support team available to resolve queries and help optimize your DeFi strategies.
    Comprehensive Analytics: Leverage data-driven insights to make informed decisions, tailor your yield farming, and monitor performance.
    Getting Started with Stargate Finance
    Ready to dive into the world of DeFi with Stargate Finance? Here’s a quick guide to get you started:

    Visit the and create your account.
    Connect your crypto wallet to begin accessing the features.
    Explore liquidity pools and start yield farming to optimize your returns.
    With these resources, you can securely and efficiently manage your decentralized financial strategies.

    Conclusion
    Stargate Finance empowers you to confidently participate in the DeFi landscape, offering secure, efficient, and user-friendly solutions for the modern investor. Discover what it means to have a true gateway to financial freedom and innovation with Stargate Finance.

    For more information and to get started today, .

    Understanding Stargate Finance Token
    The Stargate Finance Token is an integral part of the blockchain ecosystem, especially for those involved in decentralized finance (DeFi). As a bridge to seamless blockchain transactions, it plays a crucial role in enhancing interoperability across different networks.

    Key Features of Stargate Finance Token
    Stargate Finance Token stands out in the DeFi space for several reasons. Here are its key features:

    Interoperability: Facilitates cross-blockchain transactions with ease.
    Scalability: Designed to handle a large volume of transactions.
    Security: Incorporates advanced security protocols for secure transfers.
    Liquidity Pools: Offers attractive opportunities for liquidity providers.
    Benefits of Using Stargate Finance Token
    Using the Stargate Finance Token provides several benefits to investors and users:

    Cost Efficiency: Reduces transaction fees compared to traditional methods.
    Speed: Transfers are quick, minimizing waiting times.
    Investment Potential: Opportunity for profitable returns through staking and liquidity.
    Innovation: Continuously updates to incorporate the latest in blockchain technology.
    How to Get Started with Stargate Finance Token
    Getting started with Stargate Finance Token is straightforward:

    Visit a reputable that lists Stargate tokens.
    Create an account and complete any necessary verification.
    Deposit funds into your account via fiat or cryptocurrency transfer.
    Purchase Stargate Finance Tokens from the exchange market.
    Consider joining liquidity pools or staking to maximize your returns.

  8. DannyUnded表示:

    How Nigeria’s biggest city became the world’s hottest winter party destination
    casino bonus

    It’s a world of endless parties and sleepless nights. A relentless celebration that turns West Africa – and especially Nigeria’s largest city, Lagos – into one of the hottest destinations on the continent, if not the planet, right in the middle of winter.

    Detty December is a magical time between December and early January when diaspora communities and tourists flock to Ghana, Nigeria and South Africa for an unforgettable experience filled with flavourful food, soulful African music and sunshine.

    Beach parties, festivals and top-tier performances fuel the energy, while fashion takes center stage, with everyone dressing to impress.

    Nearly two-thirds of Nigeria’s population is under 25, according to the United Nations Population Fund, making this one of the world’s youngest countries.

    Internationally renowned Afrobeats performers and foreign artists make surprise appearances. DJs take to the streets, blasting powerful beats from consoles mounted atop bright yellow minibuses.

    At times it’s all-consuming. Good luck getting hair salon appointments, affordable air tickets or navigating Lagos’ already notorious traffic when the party crowds are in town.

    Detty December (“detty” is a playful corruption of “dirty”) is a triumphant celebration of culture, music and good vibes that has evolved in recent years during the traditional holidays influx of diaspora returnees, which heightened in 2018 when Ghana ran a launched a successful “Year of Return” campaign actively encouraging people to visit their ancestral homelands.

    It’s gathered pace over the past five years, gaining an international reputation, as IJGBs (“I Just Got Backs”) and their friends arrive in batches, eager to unwind and blow off steam after the fast-paced, hard-working year they’ve had overseas.

    For many in the vast Nigerian diaspora, it is a deeply personal homecoming, a chance to reconnect with their heritage, traditions and families while immersing themselves in the lively energy of Nigerian life.

  9. This could be delicately scraped with a stone instrument to give relief and variation to the coloration.

  10. Donaldabula表示:

    buy ed pills online fast pills easy ed online treatment

  11. A dominant strategy is a method that is always essentially the most more likely to result in success, making it objectively one of the best strategy.

  12. Petervop表示:

    Understanding the Aave Protocol
    The Aave Protocol is revolutionizing the decentralized finance (DeFi) space with its unique approach to crypto lending and borrowing. Whether you’re a seasoned investor or new to the world of cryptocurrencies, Aave offers a robust platform for managing your digital assets.
    aave protocol
    What is Aave?
    Aave, which means ‘ghost’ in Finnish, is a non-custodial liquidity protocol. It allows users to earn interest on deposits and borrow assets. Aave is known for its wide range of supported cryptocurrencies and features that enhance the security and flexibility of crypto transactions.

    Key Features of Aave Protocol
    Flash Loans: Aave introduced the concept of flash loans, which are borrowed and repaid within a single transaction. This feature is useful for arbitrage opportunities and collateral swaps.
    Security: Aave is audited by leading blockchain security firms, ensuring the safety of user funds.
    Rate Switching: Users can switch between stable and variable interest rates, offering flexibility based on market conditions.
    Wide Asset Support: Aave supports multiple cryptocurrencies including Ethereum (ETH), DAI, and more.
    How to Get Started with Aave
    Getting started with Aave is straightforward:

    Set Up a Wallet: Use a compatible crypto wallet like MetaMask.
    Connect to Aave: Visit the Aave website and connect your wallet.
    Deposit Crypto: Choose from supported cryptocurrencies to deposit into the Aave Protocol.
    Start Earning or Borrowing: Once your crypto is deposited, you can start earning interest or borrowing assets instantly.
    Advantages of Using Aave
    There are several reasons why Aave stands out in the world of DeFi:

    Non-Custodial: Users maintain control over their funds.
    Highly Secure: Regular audits and community governance enhance security.
    Innovative Products: Pioneering features like flash loans provide unparalleled opportunities.
    In conclusion, the Aave Protocol offers a revolutionary platform for anyone looking to explore the potential of decentralized finance. Whether you’re earning interest or borrowing assets, Aave provides a secure and flexible experience.

  13. A friend of mine advised this site. And yes. it has some useful pieces of info and I enjoyed scaning it. Therefore i would love to drop you a quick note to express my thank. Take care

  14. Откачка канализации в Слуцке, быстро.
    Не откладывайте проблему с канализацией в Слуцке, по выгодной цене.
    Профессиональные услуги по откачке канализации в Слуцке, со скидкой.
    Актуальные услуги откачки канализации в Слуцке, со скидкой для постоянных клиентов.
    Откачка канализации в Слуцке: вызовите профессионалов, по круглосуточно.
    Профессиональная откачка канализации в Слуцке: решение вопроса быстро, с гарантией качества.
    Закажите откачку канализации в Слуцке у профессионалов, с гарантией качества работы.
    Экстренная откачка канализации в Слуцке, с гарантией качества.
    Служба откачки канализации в Слуцке: быстрое решение проблем, с использованием современного оборудования.
    откачка канализации Слуцк откачка септиков Слуцк .

  15. BrettTIT表示:

    Cheap generic Viagra online: FastPillsForMen – Sildenafil Citrate Tablets 100mg

  16. сравнение производительности процессоров [url=https://www.topcpu.ru]https://www.topcpu.ru[/url] .

  17. kubet88表示:

    I think it is a nice point of view. I most often meet people who rather say what they suppose others want to hear. Good and well written! I will come back to your site for sure!

  18. сравнение процессоров для пк http://topcpu.ru/ .

  19. ku11表示:

    These kind of posts are always inspiring and I prefer to read quality content so I happy to find many good point here in the post. writing is simply wonderful! thank you for the post

  20. Michaelvof表示:

    Maximizing Profits with 1inch Exchange
    In the fast-paced world of cryptocurrency, every second counts. 1inch Exchange offers a powerful solution for traders looking to optimize their crypto transactions. By aggregating the best deals across various decentralized exchanges (DEXs), 1inch ensures users get the most value for their trades.
    1inch exchange
    What is 1inch Exchange?
    1inch Exchange is a decentralized exchange aggregator. It searches multiple DEXs to find the most efficient path for your trade, thus minimizing costs and maximizing returns. By splitting your transaction into parts and executing them across different platforms, 1inch achieves the best possible market rates.

    Key Benefits of Using 1inch Exchange
    Cost Efficiency: By seeking the best rates across multiple platforms, 1inch saves you money on each transaction.
    Security: Operating on a decentralized network means that your assets are secure and you maintain control of your keys.
    Liquidity: Access a vast pool of liquidity across numerous exchanges, ensuring that your trades are executed quickly and with minimal slippage.
    How Does 1inch Work?
    1inch deploys a sophisticated algorithm that splits your trade across multiple exchanges. This process uses smart contracts to ensure every part of the transaction is executed seamlessly and securely. 1inch’s pathfinder algorithm analyzes multiple liquidity sources within seconds to find the best exchange rates for your trade.

    Getting Started with 1inch
    Getting started with 1inch Exchange is easy. Follow these simple steps:

    Visit the 1inch website and connect your digital wallet.
    Select the token you wish to trade and the token you want to receive.
    1inch displays the best available rates and allows you to execute the trade directly from the platform.
    Conclusion
    1inch Exchange is an invaluable tool for cryptocurrency traders looking to enhance their trading efficiency. By securing the best rates and offering robust security measures, 1inch stands out as a top choice for optimizing crypto swaps. Explore 1inch today and take your trading to the next level.

  21. Charlesbot表示:

    http://maxpillsformen.com/# Tadalafil price

  22. mfgebkjva表示:

    Selon les clauses du contrat, le logo MelBet apparaîtra sur les panneaux publicitaires à LED de l’Allianz Stadium. La société pourra également proposer à ses clients des billets VIP pour les matchs à domicile, des visites exclusives du stade et de la marchandise signée. En suivant ces étapes simples, vous pouvez facilement installer l’app Melbet en Afrique et sur votre appareil Android et commencer à profiter de tous ses avantages. Téléchargez l’application et découvrez pourquoi tant de parieurs en Afrique choisissent Melbet pour leurs paris sportifs ! À l’instar de tous les autres bookmakers, il n’est pas possible de parier sur Melbet sans avoir de compte chez le bookmaker. Pour s’inscrire, rien de plus simple. Choisissez « Inscription » lorsque vous êtes sur le site du bookmaker, puis faites votre choix entre quatre options différentes, à savoir :
    http://lulisara1980.raidersfanteamshop.com/informations-grandbay
    Gagner la montée sur le terrain, c’est mieux Maison du Sport français1 avenue Pierre de Coubertin75013 PARIS Dans l’éventualité où vous prenez votre poste dans un club au budget de transferts négatif, vos débuts sur le banc de touche seront plus épineux. 4 j’aime Découvrir Avez-vous trouvé un prix plus bas ? Dites-le-nous. Nous ne pouvons pas égaler chaque prix indiqué, mais nous allons utiliser vos idées pour garantir la compétitivité de nos prix. Pour en savoir plus sur la gestion de vos données par Webedia et vos droits, consultez notre politique de protection des données. Journaliste, rédaction des sports de Châteauroux Biagio, originaire de Mendoza comme son ami Joaquin, mais vivant lui en France depuis 7 ans, dit aussi « comprendre la situation ». « On aurait fait pareil si les JO étaient chez nous en Argentine », sourit-il, avec son maillot des Pumas sur le dos. Le jeune homme revient sur le chant raciste envers les Français, partagé par le footballeur Enzo Fernandez après le succès argentin en Copa America en juillet, qui a provoqué une polémique à la limite de l’incident diplomatique entre les deux pays.

  23. Diplomi_aapi表示:

    дипломная работа на заказ дипломная работа на заказ .

  24. kubet77表示:

    I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  25. Donaldabula表示:

    Tadalafil Tablet Max Pills For Men Generic Tadalafil 20mg price

  26. WilliamDam表示:

    Aerodrome Finance: Unlocking Potential for Growth
    The world of aerodrome finance is pivotal for ensuring the efficient operation, enhancement, and expansion of aerodrome facilities globally. With the increasing demand for air travel, understanding aerodrome financial processes is more important than ever.
    aerodrome swap
    Why Aerodrome Finance Matters
    Aerodrome finance plays a critical role in the lifespan of airport projects, providing necessary funding from initial development to ongoing management. Here are key reasons why it matters:

    Infrastructure Development: Secure financial backing enables the construction and maintenance of essential airport infrastructure.
    Operational Efficiency: Adequate funding ensures that airports can operate smoothly, adapting to technological advancements and logistical demands.
    Economic Growth: Airports serve as economic hubs; their development stimulates job creation and boosts local economies.
    Aerodrome Finance Strategies
    Various strategies can be employed to optimize aerodrome finance, ensuring both immediate and long-term benefits. Here are a few notable approaches:

    Public-Private Partnerships (PPP)
    These partnerships combine public sector oversight and private sector efficiency, leading to shared risks and rewards. They facilitate diverse financial resources and innovative solutions for airport projects.

    Revenue Diversification
    Exploring non-aeronautical revenue streams, such as retail concessions and property leases, can significantly bolster an airport’s financial resilience. Such diversification allows for a steady income flow independent of ticket sales.

    Sustainable Financing
    Adopting sustainable financial practices, including green bonds and ESG (Environmental, Social, and Governance) criteria, aligns with modern ecological standards and attracts environmentally conscious investors.

    Challenges and Opportunities
    While aerodrome finance offers numerous benefits, it also poses certain challenges. High capital costs, regulatory hurdles, and fluctuating passenger demands can impact financial stability. However, these challenges also present opportunities for innovation and improvement.

    Tech-Driven Solutions: Embracing technology like AI and predictive analytics can enhance decision-making and financial planning.
    Collaboration: Strengthening ties with stakeholders, including airlines and government agencies, can streamline financial operations and capital investments.
    Ultimately, the goal of aerodrome finance is to support the sustainable growth and modernization of airports, ensuring their pivotal role in global connectivity remains strong.

  27. Magnificent beat ! Can I be your apprentice? Just kidding!

  28. Barrybib表示:

    ed med online: cheapest online ed treatment – low cost ed medication

發佈留言

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