带有添加和删除功能的表格

本文介绍了一种实现网页中回顶按钮与固定头部效果的方法。通过监听滚动事件,根据页面滚动高度来显示或隐藏顶部通栏和回顶按钮。当页面滚动到一定高度时,顶部通栏和回顶按钮将显示出来;点击回顶按钮,页面会平滑滚动到顶部。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      height: 3000px;
    }

    .topBar {
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
      color: #fff;
      background-color: skyblue;
      position: fixed;
      font-size: 30px;
      left: 0;
      top: 0;

      display: none;
    }

    .topBar.active {
      display: block;
    }

    .goTop {
      width: 50px;
      height: 50px;
      line-height: 25px;
      font-size: 20px;
      color: #fff;
      background-color: pink;
      position: fixed;
      bottom: 50px;
      right: 50px;
      text-align: center;
      cursor: pointer;

      opacity: 0;
      transition: opacity .5s linear;
    }

    .goTop.active {
      opacity: 1;
    }
  </style>
</head>
<body>

  <div class="topBar">顶部通栏</div>
  <div class="goTop">回到顶部</div>

  <script>
    /*
      作业: 回到顶部

      代码实现:
        1. 获取元素
          => 顶部通栏
          => 回到顶部按钮
        2. 操作两个盒子显示和隐藏
          => 使用 window.onscroll 事件
          => 再事件里面随时获取浏览器卷去的高度
          => 通过卷去的高度判断(自己定一个边界值)
          => 操作显示
            -> 添加类名 active
          => 操作隐藏
            -> 取消类名 active
          => 用哪种方式添加和取消
            1. className - 好加不好去
            2. classList - 随便
        3. 点击回到顶部按钮的时候, 滚动条回到顶部
          => 给 goTop 按钮绑定一个点击事件
          => 再事件处理函数里面使用 scrollTo()
    */

    // 1. 获取元素
    var topBar = document.querySelector('.topBar')
    var goTop = document.querySelector('.goTop')

    // 2. 操作两个盒子显示隐藏
    window.onscroll = function () {
      // 2-2. 获取浏览器卷去的高度
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

      // 2-3. 自己定一个边界值进行判断(300)
      if (scrollTop >= 300) {
        // 两个盒子显示
        // className
        // topBar.className = 'topBar active'
        // goTop.className = 'goTop active'
        // classList
        topBar.classList.add('active')
        goTop.classList.add('active')
      } else {
        // 两个盒子隐藏
        // topBar.className = 'topBar'
        // goTop.className = 'goTop'

        topBar.classList.remove('active')
        goTop.classList.remove('active')
      }
    }

    // 3. 回到顶部
    goTop.onclick = function () {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }
  </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值