英文 | https://www.ibrahima-ndaw.com/blog/parallax-effect-with-10-lines-of-javascript/
翻譯 | web前端開發(web_qdkf)
在本文中,我們將使用HTML,CSS和僅10行JavaScript代碼來製作一個漂亮的視差效果。
首先,我們來看一下最終完成的視差效果的動畫圖:
<main> <header> <div> <i></i> <h3>Welcome</h3> <p>Scroll to see how cool i am!</p> </div> </header>
<section> <h3>Cool like you</h3> </section></main>然後,我們使用兩個標籤製作視差效果。第一個標記header包含頁面加載時顯示的元素,第二個標記section將在滾動時觸發以啟動效果。
CSS
在CSS這部分裡,我們需要先進行一些CSS的設置,然後將需要的字體進行導入進來,代碼如下:
@import url("https://fonts.googleapis.com/css?family=Courgette:400,700&display=swap");* { margin: 0; padding: 0; box-sizing: border-box;}
body { background: linear-gradient(135deg, #0056a7, #165fa3, #477aaa); font-family: "Courgette", cursive;}
header { display: flex; justify-content: center; align-items: center; flex-direction: column; position: relative; height: 100vh; color: #eee; z-index: -1; text-align: center; animation: fadeIn 1.5s ease-in-out;}接著,我們用position:relative控制header標籤的位置,當效果開始時,屬性z-index:-1會將header標籤放置在section元素後面。
section { display: flex; align-items: center; justify-content: center; z-index: 1; height: 100vh; font-size: 5rem; background: #fcdb6d; color: #0056a7;}在這裡,我們為section選擇器使用了相反的方法,即當z-index屬性滾動為1時,則section標記裡面的字放置在header上方。
.animate-me { animation: bounceIn 3s ease-in-out;}
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; }}
@keyframes bounceIn { 0% { transform: scale(0.1); opacity: 0; } 60% { transform: scale(1.2); opacity: 1; } 100% { transform: scale(1); }}最後,雖然不是最不重要的一點,但我們為元素入口製作了一些動畫。section的反彈效果和header的褪色效果。該類animate-me將section通過JavaScript添加到後面。
JavaScript
最後,我們通過使用JavaScript,讓效果在滾動時產生視差效果。
window.addEventListener("scroll", function() { const distance = window.scrollY document.querySelector("header").style.transform = `translateY(${distance * 1}px)` document.querySelector( ".container" ).style.transform = `translateY(${distance * 0.3}px)` setTimeout(() => { document.querySelector("section h3").classList.add("animate-me") }, 400)})如你在這裡看到的,我們收聽scroll事件以開始效果。
然後,我們將通過Y軸(垂直)distance的數量分配給常量scroll。然後從DOM中選擇所需的元素並訪問該transform屬性。這樣,我們現在就可以使用該translateY值動態地將賦值給translateY。該值header與其子元素之間有所不同container,只是效果更平滑。然後,通過添加彈跳效果標題的animate-me類來完成所有操作section。