簡體   English   中英

如何使用 HTML + CSS + JS(有限)在滾動上創建簡單的視差?

[英]How to create simple parallax on scroll using HTML + CSS + JS (limited)?

我遇到的問題是在沒有任何額外的 HTML 元素的情況下在身體上創建一個簡單的視差效果

設置: <body>具有固定的背景圖像和 background-size:cover;。 body 的所有直接子級都有背景顏色,但是用於顯示body 背景圖片的<header>

如果您打算使用background-size:cover; , 然后position:sticky; 頂部的酒吧是必須的。

出於說明目的:

<body>
<nav style='background: white;height:160px;position:sticky;top:0px;'></nav>
<header id='see_through'>This works as the "window" for body background picture</header>
<main style='background: white;'></main>
<footer style='background: white;'></footer>
</body>

當前CSS代碼:

body {
background:url('header-background.jpg');
background-position:center bottom;
background-attachment:fixed;
background-repeat:no-repeat;
background-size:cover;
}

我可以在 Google 或 Stackoverflow 上找到的所有示例都涉及使用某些庫(主要是 jQuery)或一些擴展代碼和/或額外的 HTML 元素。

我擁有的主要條件是 - 沒有 HTML 更改,如果可能的話也沒有圖書館。

解決方案包括為滾動事件添加一個 eventListener。

window.addEventListener('scroll', function(){
    scroll_position = window.scrollY; /* Current scroll position */
    header_height = document.getElementById('see_through').clientHeight; /* header height */
    /* Parallax height can't be more than sticky bars' height, applies only when using background-size:cover; */
    parallax_height_max = 160;
    if(scroll_position > header_height){ /* if scroll position is past header, basically ignore */
        position = 0;
    }else{
        position = parallax_height_max - Math.floor(scroll_position / header_height * parallax_height_max); /* calculate relative position of background image */
    }
    /* set new background vertical position, this can be moved to ELSE part, depending on your requirements */
    document.body.style.setProperty('background-position-y', position + 'px');
});

而 CSS 添加包括:

body {
transition:background-position ease-in-out; /* optional */
background-position-y:160px; /* initial position */
}

所以整個效果是基於一個透明元素前后都有一個不透明元素,但應該在不同的場景下可調(固定元素大小,windows 邊框)。

Javascript 部分已清理/最小化(移除部分,動態較小):

window.addEventListener('scroll', function(){
    header_height = document.getElementById('see_through').clientHeight;
    if(window.scrollY < header_height){
        document.body.style.setProperty('background-position-y', (160 - Math.floor(window.scrollY / header_height * 160)) + 'px');
    }
});

我希望這有幫助。

暫無
暫無

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

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