如何使用JavaScript实现页面加载时文本的闪烁高亮效果
Solution for Page-Load Element Highlight (Two Flashes)
Got it! Here's a vanilla JavaScript + CSS solution that creates a cross-browser compatible highlight effect around your target element—flashing twice and disappearing automatically once the page finishes loading. No external libraries needed, so it’s lightweight and works across most browsers.
Full Working Code
<!DOCTYPE html> <html lang="en"> <head> <style> /* Define the flash animation with cross-browser prefixes */ @keyframes flashHighlight { 0% { outline: 3px solid #ffd700; } 50% { outline: 3px solid transparent; } 100% { outline: 3px solid #ffd700; } } @-webkit-keyframes flashHighlight { 0% { outline: 3px solid #ffd700; } 50% { outline: 3px solid transparent; } 100% { outline: 3px solid #ffd700; } } /* Animation class to trigger the effect */ .flash-animation { animation: flashHighlight 0.8s ease-in-out 2; -webkit-animation: flashHighlight 0.8s ease-in-out 2; /* Prevent highlight from shifting page layout */ outline-offset: 2px; } </style> </head> <body> <div id="highlight-me">A bit of text needing attention on page landing.</div> <script> // Wait for the DOM to be fully ready before triggering the effect window.addEventListener('DOMContentLoaded', function() { const targetElement = document.getElementById('highlight-me'); // Add the animation class to start the flashes targetElement.classList.add('flash-animation'); // Clean up the class once the animation finishes (runs only once) targetElement.addEventListener('animationend', function() { targetElement.classList.remove('flash-animation'); }, { once: true }); }); </script> </body> </html>
Key Details & Compatibility
- Cross-browser support: Includes
-webkit-prefixes to work with older Chrome, Safari, and Edge versions (covers browsers back to IE11—if you need full IE11 support, just let me know and I can tweak the animation syntax). - Layout-friendly: Uses
outlineinstead ofborderso the highlight doesn’t push other elements around, andoutline-offsetadds a little space between the element and the highlight. - Clean execution: The
animationendlistener with{ once: true }ensures we only remove the animation class once, avoiding any unexpected re-runs.
Quick Customization Tips
- Change highlight style: Swap
outlineforbox-shadow(e.g.,box-shadow: 0 0 12px #ff4500;) for a softer glow effect. - Adjust speed: Modify the
0.8svalue in the animation property to make flashes faster or slower. - Tweak color: Replace
#ffd700(gold) with any hex/rgb color that matches your design. - Change flash count: Update the
2at the end of the animation property to your desired number of flashes.
内容的提问来源于stack exchange,提问作者ptrcao
相关产品推荐
相关产品推荐

