用10行JavaScript代碼制作一款漂亮的視差效果

英文 |?https://www.ibrahima-ndaw.com/blog/parallax-effect-with-10-lines-of-javascript/
翻譯 | web前端開(kāi)發(fā)(web_qdkf)
在本文中,我們將使用HTML,CSS和僅10行JavaScript代碼來(lái)制作一個(gè)漂亮的視差效果。
首先,我們來(lái)看一下最終完成的視差效果的動(dòng)畫(huà)圖:

Welcome
Scroll to see how cool i am!
Cool like you
然后,我們使用兩個(gè)標(biāo)簽制作視差效果。第一個(gè)標(biāo)記header包含頁(yè)面加載時(shí)顯示的元素,第二個(gè)標(biāo)記section將在滾動(dòng)時(shí)觸發(fā)以啟動(dòng)效果。
CSS
在CSS這部分里,我們需要先進(jìn)行一些CSS的設(shè)置,然后將需要的字體進(jìn)行導(dǎo)入進(jìn)來(lái),代碼如下:
@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標(biāo)簽的位置,當(dāng)效果開(kāi)始時(shí),屬性z-index:-1會(huì)將header標(biāo)簽放置在section元素后面。
section {display: flex;align-items: center;justify-content: center;z-index: 1;height: 100vh;font-size: 5rem;background: #fcdb6d;color: #0056a7;}
在這里,我們?yōu)閟ection選擇器使用了相反的方法,即當(dāng)z-index屬性滾動(dòng)為1時(shí),則section標(biāo)記里面的字放置在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);}}
最后,雖然不是最不重要的一點(diǎn),但我們?yōu)樵厝肟谥谱髁艘恍﹦?dòng)畫(huà)。section的反彈效果和header的褪色效果。該類animate-me將section通過(guò)JavaScript添加到后面。
JavaScript
最后,我們通過(guò)使用JavaScript,讓效果在滾動(dòng)時(shí)產(chǎn)生視差效果。
window.addEventListener("scroll", function() {const distance = window.scrollYdocument.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)})
然后,我們將通過(guò)Y軸(垂直)distance的數(shù)量分配給常量scroll。然后從DOM中選擇所需的元素并訪問(wèn)該transform屬性。


