简体   繁体   中英

Random background on refresh + background change on hover

I've got a page wherein I want the background image of a container to be randomized on refresh. I also want to be able to change the background image on hover and have it revert to the current random selection post-hover state. Essentially, I want to combine these two effects:

https://codepen.io/sallymargaret/pen/mdMORLM and https://codepen.io/sallymargaret/pen/LYjbxdZ

So that if, say, you land on the page and the balloon background is selected by the randomizer, the container background will revert to the balloons after the hover state is complete.

I've tried inserting 'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ') into onmouseleave (ie, ending up with $('#menu1').on('mouseleave', function(){ $('#header-image-wrapper').css('background-image', 'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ')');}); with no luck.

I'm super new to JS and have cobbled all this code together from various questions so apologies in advance if I'm making a faff of it and missing something key and easy.

I removed logo and menu1 , because you dont use them. You can try the random by running the snippet a bunch of time.

 const heroPics = ['https://www.dontwasteyourmoney.com/wp-content/uploads/2020/08/best-balloons-900x400.jpeg', 'https://sqlundercover.files.wordpress.com/2021/03/dice.jpg', 'https://pbs.twimg.com/profile_images/653700295395016708/WjGTnKGQ.png']; const gif = "https://static.tumblr.com/foq3nys/2Wzr07uya/dan_typing.gif" // I remove menu1 and logo. We dont need that for our example const selected = heroPics[Math.floor(Math.random()*heroPics.length)]; $('#menu2').on('mouseenter', function() { $('#header-image-wrapper').css('background-image', `url(${gif})`); }); $('#menu2').on('mouseleave', function() { $('#header-image-wrapper').css('background-image', `url(${selected})`); }); // initialize the selected image $('#header-image-wrapper').css('background-image', `url(${selected})`);
 body { margin: 0; } .header-image-wrapper { height: 100vh; transition: background .3s linear; background: #f0d4eb no-repeat center; background-size: cover; } .open-project { color: #fff; font-weight: 700; font-size: 50px; margin: 0 auto; transition: all .2s ease-in-out; } .open-project:hover { opacity: .3; padding-left: 10px; } #header-image-wrapper { background-image: ; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="header-image-wrapper" id="header-image-wrapper"> <div class="open-project-link"> <a id="menu2" class="open-project" href="http://">link 1</a> </div> </div>

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