【Html】js+css实现平滑滚动

这篇文章展示了如何使用HTML、CSS和JavaScript实现网页的平滑滚动效果,特别是当用户点击回到顶部按钮时。通过设置CSS的`scroll-behavior:smooth`属性和JavaScript的`window.scrollTo`方法,可以创建一个平滑滚动到页面顶部的交互体验。示例代码包括一个固定在底部的按钮以及多个图片示例。
摘要由CSDN通过智能技术生成

效果

在这里插入图片描述

示例

<!DOCTYPE html>
<html>
  <head>
    <title> Document </title>
    <style>
      button{
        bottom: 0;
        position: fixed;
        z-index: 999;
        left: 0;
        background: rgb(94, 171, 255);
        border: 1px red;
        color: white;
        font-size: large;
        font-family: '';
      }
    img{
      position: relative;
      cursor: not-allowed;
      width: 100%;
      height: 100%;
      z-index: 0;
    }
    /*方式一:配合 “window.scrollTo(0,0);” 一起设置滚动行为:平滑*/
     html{
      scroll-behavior: smooth;
    } 
  </style>
  </head>
  <body>
    <button class="btn">回到顶部</button>
    <img src="https://picsum.photos/seed/1/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/2/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/3/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/4/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/5/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/6/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/7/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/8/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/9/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/10/800/600.jpg" alt=""/>
    <script>
    const btn = document.querySelector('.btn');
    btn.onclick = () => {
      //直接回到顶部
      window.scrollTo(0,0);

      /* 方式二:设置滚动到顶部行为:平滑*/
      /* window.scrollTo({
        top:0,
        behavior:"smooth"
      }); */
    }
  </script>
  </body>
</html>

推荐两种方式

方式一

第一步、使用js设置滚动位置

window.scrollTo(0,0);设置为滚动位置为x=0,y=0

    <script>
    const btn = document.querySelector('.btn');
    btn.onclick = () => {
      //直接回到顶部
      window.scrollTo(0,0);
    }
  </script>

第二步、使用css设置html的滚动行为

     html{
      scroll-behavior: smooth;
    } 

方式二

直接使用window.scrollTo设置滚动位置及滚动行为

      window.scrollTo({
        top:0,
        behavior:"smooth"
      });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值