簡體   English   中英

刷新時的隨機背景 + 懸停時的背景變化

[英]Random background on refresh + background change on hover

我有一個頁面,我希望在刷新時隨機化容器的背景圖像。 希望能夠在懸停時更改背景圖像,並使其恢復到當前的隨機選擇后懸停狀態。 本質上,我想結合這兩種效果:

https://codepen.io/sallymargaret/pen/mdMORLMhttps://codepen.io/sallymargaret/pen/LYjbxdZ

因此,如果您登陸頁面並且隨機生成器選擇了氣球背景,則容器背景將在懸停狀態完成后恢復為氣球。

我試過將'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ')插入onmouseleave (即,以$('#menu1').on('mouseleave', function(){ $('#header-image-wrapper').css('background-image', 'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ')');});沒有運氣。

我是 JS 的超級新手,並且已經將所有這些代碼從各種問題拼湊在一起,所以如果我對它大肆吹捧並且遺漏了一些關鍵和簡單的東西,請提前道歉。

我刪除了logomenu1 ,因為你不使用它們。 您可以通過多次運行代碼段來嘗試隨機。

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM