繁体   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