点击按钮,让页面滚动到指定位置的方法

91 篇文章 1 订阅

1.喵点

2.ele.scrollIntoView()

关于scrollIntoView方法:

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    ul {
      margin: 20px 0;
    }

    .item-style {
      height: 200px;
      margin: 20px 0;
      list-style: none;
      border: 1px solid #d6d6d6;
      font-size: 90px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .item-style:nth-child(2n) {
      background-color: cornflowerblue;
    }

    .item-style:nth-child(2n+1) {
      background-color: burlywood;
    }

    #input-style {
      width: 100%;
      height: 50px;
      font-size: 40px;
    }

    .btn-style {
      height: 60px;
      border-radius: 4px;
      border: none;
      background-color: darkcyan;
      font-size: 30px;
      color: #fff;
      margin: 20px;
    }
  </style>
</head>
<body>
<button onclick="moveCenter()" class="btn-style">
  测试scrollIntoViewIfNeeded---true
</button>
<button onclick="moveOther()" class="btn-style">
  测试scrollIntoViewIfNeeded---false
</button>
<button onclick="moveScrollIntoView(true)" class="btn-style">
  测试scrollIntoView--true
</button>
<button onclick="moveScrollIntoView(false)" class="btn-style">
  测试scrollIntoView--false
</button>
<button onclick="moveScrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'})"
        class="btn-style">
  测试scrollIntoView--动画
</button>
<ul>
  <li class="item-style">
    1
  </li>
  <li class="item-style">
    2
  </li>
  <li class="item-style">
    3
  </li>
  <li class="item-style">
    4
  </li>
  <input type="text" placeholder="请输入" id="input-style" />
  <li class="item-style">
    5
  </li>
  <li class="item-style">
    6
  </li>
  <li class="item-style">
    7
  </li>
  <li class="item-style">
    8
  </li>
</ul>
<script>
  var ele = document.getElementById('input-style')

  // 测试元素将在其所在滚动区的可视区域中居中对齐
  function moveCenter() {
    setTimeout(() => {
        ele.scrollIntoViewIfNeeded()
      },
      500)
  }

  // 测试元素将与其所在滚动区的可视区域最近的边缘对齐
  function moveOther() {
    setTimeout(() => {
        ele.scrollIntoViewIfNeeded(false)
      },
      500)
  }

  // 测试scrollIntoView, 根据可见区域最靠近元素的哪个边缘,
  //元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。
  function moveScrollIntoView(content) {
    setTimeout(() => {
        ele.scrollIntoView(content)
      },
      500)
  }
</script>
</body>
</html>

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值