let dubaitext = document.getElementById('dubaitext');
let burjkhalifa = document.getElementById('burjkhalifa');
let stars = document.getElementById('stars');
window.addEventListener('scroll', () => {
let value = window.scrollY;
burjkhalifa.style.top = value * 1.5 + 'px';
});
* {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
box-sizing: border-box;
}
body {
background: linear-gradient(to left , #423bcf8e , #b7aeff, #a4b3cda7, #031973);
min-height: 100vh;
overflow-x: hidden;
}
.parallax{
position: relative;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.parallax img{
position: absolute;
top: 0;
left: 0;
width:100wh;
pointer-events: none;
}
#building {
position: absolute;
width: 85%; /* Adjust the percentage to scale the image down */
height: auto; /* Maintain the aspect ratio */
}
#burjkhalifa{
position: absolute;
width: 85%;
height: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href = "style.css">
<title>Document</title>
</head>
<body>
<section class="parallax">
<img src="images/burjkhalifa.png" id="burjkhalifa">
<img src="images/building.png" id="building">
</section>
<script src="script.js"></script>
</body>
</html>
我目前正在学习如何在我的网站上实现视差效果。尽管密切关注教程,我还是遇到了图像的定位和移动问题。我面临的问题是,当我向下滚动时,burjkhalifa 图像会滚动出视口。尽管尝试调整图像大小和位置,问题仍然存在。在我遵循的教程中,图像在滚动时保持在视口内。
任何人都可以帮我解决这个问题并确保图像很好地适应视差效果而不滚动到视图之外吗?
在此示例中:
我们有一个 .parallax-container div 作为视差层的容器。 在这个容器内,我们有两个视差层 .layer1 和 .layer2。 .parallax-layer 类将图层绝对定位在容器内,并使它们覆盖整个视口。 我们使用背景图片为每一层设置背景图片
body, html {
margin: 0;
padding: 0;
}
.parallax-container {
position: relative;
width: 100%;
height: 100vh; /* Adjust height as needed */
overflow: hidden;
}
.parallax-layer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 200%; /* Adjust height as needed */
background-size: cover;
background-position: center;
}
.layer1 {
background-image: url('image1.jpg');
z-index: -1; /* Ensure it's behind content */
}
.layer2 {
background-image: url('image2.jpg');
z-index: -2; /* Ensure it's behind content and other layer */
}
.content {
padding: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parallax Effect</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="parallax-container">
<div class="parallax-layer layer1"></div>
<div class="parallax-layer layer2"></div>
</div>
<div class="content">
<h1>Welcome to My Website</h1>
<p>This is some sample content.</p>
</div>
</body>
</html>
财产。 .content div 包含页面上的其余内容。 您可以根据需要调整高度、背景图像和其他属性,以实现所需的视差效果。确保将“image1.jpg”和“image2.jpg”替换为实际图像文件的路径。