简体   繁体   中英

SVG Preloader with CSS animation that randomizes on each page load

So i made a svg logo preloader, made some css animations for it also. But my main problem is how do i make the preloader load different animation on refresh/new page loading using javascript. Like for example on one page loading the logo should use the bounce animation and upon a page refreh or on another tab opening the preloader to use the rotate animation i made, etc.

 var strings = [ 'animation1.', 'animation2.', 'animation3.' ]; var rand = strings[Math.floor(Math.random() * strings.length)]; document.getElementById('loading-animation').innerHTML = rand;
 .loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; text-align: center; background: #ddd; padding-top: 200px; }.svg { display: block; width: 80px; height: 80px; background: #aaa; margin: 10px auto; }.animation1 { just an example }.animation2 { just an example }.animation2 { just an example }
 <div id="container" class='loading' > <div id='loading-animation' class='loading-animation'>Processing</div> <svg>just an example svg in inserted in the html, no external src link to it</svg> </div>

I'm pretty sure that.innerHTML shouldn't be there since the javascript file will be external linked in the head section. And i know i haven't linked all of the codes used just because it's to much code to paste here so i made a mini example, hope i can make myself understood. Thanks.

You can use JavaScript to randomly assign a CSS class to the element you want to animate. Here is an example.

 var animationClasses = [ 'animation1', 'animation2', 'animation3' ]; var choosenAnimation = animationClasses[~~(Math.random() * animationClasses.length)]; document.getElementById('elementToAnimate').classList.add(choosenAnimation);
 @keyframes grow { 0% { transform: scale(0); } 100% { transform: scale(1); } } @keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fly-down { 0% { transform: translateY(-100%); } 100% { transform: translateY(0%); } }.animation1 { width: fit-content; animation: grow 1s; }.animation2 { animation: fade 1s; }.animation3 { animation: fly-down 1s; }
 <div id="elementToAnimate">This will get a random animation</div>

A random class in the array animationClasses is assigned to elementToAnimate . Each class contains CSS for a different animation, allowing for a random animation each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM