hello ~ 今天咱来学习一个页面滚动的效果
Part 1
HTML结构
<body>
<h1>Scroll to see the animation</h1>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
<div class="box"><h2>Content</h2></div>
</body>
Part 2
CSS样式
* {
box-sizing: border-box;
}
body {
background-color: #efedd6;
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
overflow-x: hidden;
}
h1 {
margin: 10px;
}
.box {
background-color: steelblue;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
width: 400px;
height: 200px;
margin: 10px;
border-radius: 10px;
box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3);
transform: translateX(400%);
transition: transform 0.4s ease;
}
.box:nth-of-type(even) {
transform: translateX(-400%);
}
.box.show {
transform: translateX(0);
}
.box h2 {
font-size: 45px;
}
关键是:利用 translate 属性 将 奇数个和偶数个 content 分别藏在左右两边
Part 3
JavaScript逻辑
const boxes = document.querySelectorAll('.box')
window.addEventListener('scroll', checkBoxes) // 注意是给 window 绑定 scroll 事件
checkBoxes()
function checkBoxes() {
const triggerBottom = window.innerHeight / 5 * 2
boxes.forEach(box => {
const boxTop = box.getBoundingClientRect().top
if (boxTop < triggerBottom) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
})
}
// 1.
// window.innerHeight
// 语法
// var intViewportHeight = window.innerHeight;
// 值
// intViewportHeight 为浏览器窗口的视口的高度。
// window.innerHeight 属性为只读,且没有默认值。
// 2.
// Element.getBoundingClientRect() 方法返回一个 DOMRect 对象,其提供了元素的大小及其相对于视口的位置。
// 语法
// getBoundingClientRect()
// Copy to ClipboardCopy to ClipboardCopy to ClipboardCopy to Clipboard
// 参数
// 无。
// 返回值
// 返回值是一个 DOMRect 对象,是包含整个元素的最小矩形(包括 padding 和 border-width)。
// 该对象使用 left、top、right、bottom、x、y、width 和 height 这几个以像素为单位的只读属性描述整个矩形的位置和大小。
// 除了 width 和 height 以外的属性是相对于视图窗口的左上角来计算的。