HTML + CSS + JavaScript 实战小项目 【页面 scroll 效果】

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 以外的属性是相对于视图窗口的左上角来计算的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值