我是一个年轻的开发人员,我每天都在尝试学习!今天,其中包括:视差。
看起来很酷很容易!
但是,以前从未发生过的事情发生在我身上,我不明白为什么...
我试图选择html元素的div:nth-childs来设置样式,但对divs无效! 我会详细说明:如果我将css放在示例中,例如:“ *:nth-child(1)”,对h2,body等都是有效的... 但是div:nth-child(1)不会选择我的div!
对于高级编码器,您猜到了我想做的事情:设置4 div的样式,而无需使用类或ID即可创建JS的视差效果。
任何提示或想法,我如何才能做到这一点?谢谢=)
https://codepen.io/Voodoobear/pen/pZxBKb
const parallax = document.getElementById("parallax");
window.addEventListener("scroll", function() {
let offset = window.pageYOffset;
parallax.style.backgroundPositionY = offset * 0.7 + "px";
})
* {
border: 0;
padding: 0;
margin: 0;
}
div {
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-family: big john;
width: 100%;
height: 100vh;
}
h2 {
font-size: 60px;
background: #eee;
padding: 8px 24px;
border-radius: 16px;
}
div:nth-child(1) {
background-image: url('https://anotherwhiskyformisterbukowski.com/wp-content/uploads/2018/02/le-web-daujourdhui-1.jpg');
background-size: cover;
}
div:nth-child(2) {
background: maroon;
}
div:nth-child(3) {
background-image: url('https://anotherwhiskyformisterbukowski.com/wp-content/uploads/2018/02/le-web-daujourdhui-1.jpg');
background-size: cover;
background-attachment: fixed;
}
div:nth-child(4) {
background: aquamarine;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Paralax</title>
</head>
<body>
<div id="parallax">
<h2>Div 1</h2>
</div>
<div>
<h2>Div 2</h2>
</div>
<div>
<h2>Div 3</h2>
</div>
<div>
<h2>Div 4</h2>
</div>
</body>
</html>