首页 > 解决方案 > 有没有办法制作没有滞后的固定背景图像?

问题描述

我尝试了很多方法将背景图像制作为固定图像。而且我已经看到他们拥有那些固定图像而不会造成滞后的网站。但遗憾的是我还没有找到方法来做到这一点。

这是我当前尝试的视频: https ://streamable.com/hkk6d6

我的代码:

import React from 'react'

const useStyles = makeStyles(theme => ({
    header: {
        position: "sticky",
        top: -63,
        zIndex: 101,
        height: "220px",
        '@media (max-width:600px)': {
            zIndex: 99,
        },
    },
    root: {
        backgroundAttachment: "fixed",
        flexWrap: "nowrap",
        flexDirection: "column",
        backgroundPosition: "50% 50%",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        height: "100%",
        width: "100%",
        display: "flex",
    }
}))
const Parallax = (props) => {
    const classes = useStyles();
    return (
        <div className={classes.root} style={{ backgroundImage: `url(${props.image})` }}>
            <div className={classes.header}>{props.header}</div>
            <div style={{ ...props.style, backgroundColor: props.theme.palette.contrast }}>{props.children}</div>
        </div>
    )
}

export const ParallaxContainer = withTheme(Parallax);

编辑:@Rounin 建议的解决方案对我来说效果很好。我还发现图像压缩并不是全部。减小高分辨率图像的大小也很重要。
对我来说,它也有帮助,将图像的大小调整为每长边最大 2000 像素。

标签: htmlcssreactjsimagestyling

解决方案


您说得对,创建视差效果的关键 CSS 属性值对是:

background-attachment: fixed;

一旦将此属性-值对应用于元素(您也可以使用速记background属性执行此操作,如下例所示),您几乎已准备就绪。

工作示例:

body {
height: 200vh;
margin-top: 180px;
}

.parallaxEffect {
width: 300px;
height: 180px;
margin: 0 auto;
background: rgb(127, 191, 255) url('https://images.pexels.com/photos/346529/pexels-photo-346529.jpeg') center / cover no-repeat fixed;
}
<div class="parallaxEffect"></div>


推荐阅读