首页 > 其他分享 >点击滚动容器内元素,滚动条自动滚动,元素水平居中或者垂直居中

点击滚动容器内元素,滚动条自动滚动,元素水平居中或者垂直居中

时间:2023-09-14 20:33:04浏览次数:30  
标签:居中 box 滚动 type 元素 scrollDom const document targetDom

话不多说,先来个完整的html例子,可以直接复制到一个html文件中看效果:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>点击居中功能</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    /* 水平居中样式 */
    .horizontal-box {
      border: 10px solid red;
      display: flex;
      flex-wrap: nowrap;
      overflow-x: auto;
    }

    .horizontal-box div {
      background: green;
      padding: 0 40px;
      margin-right: 30px;
    }

    .horizontal-box div:nth-last-child(1) {
      margin-right: 0;
    }

    /* 垂直居中样式 */
    .vertical-box {
      border: 10px solid red;
      overflow-y: auto;
    }

    .vertical-box div {
      background: green;
      height: 100px;
      margin-bottom: 30px;
    }

    .vertical-box div:nth-last-child(1) {
      margin-bottom: 0;
    }
  </style>
</head>

<body>
  <div>
    <p>点击水平居中 </p>
    <!-- position: relative一定要设置,决定了 offsetxxx 的值 -->
    <div class="horizontal-box" style="width:500px;height: 100px;position: relative;">
      <div>one</div>
      <div>two</div>
      <div>three</div>
      <div>four</div>
      <div>five</div>
      <div>six</div>
    </div>

    <p style="margin-top: 100px;">点击垂直居中 </p>
    <!-- position: relative一定要设置,决定了 offsetxxx 的值 -->
    <div class="vertical-box" style="width:100px;height: 500px;position: relative;">
      <div>one</div>
      <div>two</div>
      <div>three</div>
      <div>four</div>
      <div>five</div>
      <div>six</div>
    </div>
  </div>

  <script>
    //点击水平居中
    const domListX = document.querySelectorAll('.horizontal-box div')
    for (const dom of domListX) {
      dom.addEventListener('click', (e) => {
        const scrollDom = document.querySelector('.horizontal-box')
        const targetDom = e.target
        setScrollToCenter(scrollDom, targetDom, 'x')
      })
    }
    //点击垂直居中
    const domListY = document.querySelectorAll('.vertical-box div')
    for (const dom of domListY) {
      dom.addEventListener('click', (e) => {
        const scrollDom = document.querySelector('.vertical-box')
        const targetDom = e.target
        setScrollToCenter(scrollDom, targetDom, 'y')
      })
    }

  </script>
  <script>
    /**
      *点击元素自动滚动到水平或垂直中间位置
      * @param {HTMLElement} scrollDom - 滚动的元素
      * @param {HTMLElement} targetDom - 点击的元素
      * @param {string} [type='x'] - x表示水平,y表示垂直,默认为水平
    */
    function setScrollToCenter (scrollDom, targetDom, type = 'x') {
      if (!scrollDom || !targetDom) return false
      //如果是浏览器body的滚动条
      if ([window, document, document.documentElement].includes(scrollDom)) { scrollDom = document.documentElement }
      const { offsetLeft, offsetTop, offsetWidth, offsetHeight } = targetDom
      const { clientWidth, clientHeight } = scrollDom
      const targetDistance = type == 'x' ? offsetLeft : offsetTop
      const scrollClient = type == 'x' ? clientWidth : clientHeight
      const targetOffset = type == 'x' ? offsetWidth : offsetHeight
      const val = targetDistance - scrollClient / 2 + targetOffset / 2
      // x时,相当于:
      // targetDom.offsetLeft - scrollDom.clientWidth / 2 + targetDom.offsetWidth / 2
      // y时,相当于:
      // targetDom.offsetTop - scrollDom.clientHeight / 2 + targetDom.offsetHeight / 2
      const config = { behavior: 'smooth' }
      type === 'x' ? config.left = val : config.top = val
      scrollDom.scrollTo(config)
    }
  </script>
</body>

</html>
点击查看

 

再看效果图:

 

主要功能函数:
 /**
      *点击元素自动滚动到水平或垂直中间位置
      * @param {HTMLElement} scrollDom - 滚动的元素
      * @param {HTMLElement} targetDom - 点击的元素
      * @param {string} [type='x'] - x表示水平,y表示垂直,默认为水平
    */
    function setScrollToCenter (scrollDom, targetDom, type = 'x') {
      if (!scrollDom || !targetDom) return false
      //如果是浏览器body的滚动条
      if ([window, document, document.documentElement].includes(scrollDom)) { scrollDom = document.documentElement }
      const { offsetLeft, offsetTop, offsetWidth, offsetHeight } = targetDom
      const { clientWidth, clientHeight } = scrollDom
      const targetDistance = type == 'x' ? offsetLeft : offsetTop
      const scrollClient = type == 'x' ? clientWidth : clientHeight
      const targetOffset = type == 'x' ? offsetWidth : offsetHeight
      const val = targetDistance - scrollClient / 2 + targetOffset / 2
      // x时,相当于:
      // targetDom.offsetLeft - scrollDom.clientWidth / 2 + targetDom.offsetWidth / 2
      // y时,相当于:
      // targetDom.offsetTop - scrollDom.clientHeight / 2 + targetDom.offsetHeight / 2
      const config = { behavior: 'smooth' }
      type === 'x' ? config.left = val : config.top = val
      scrollDom.scrollTo(config)
    }
如果是body滚动,scrollDom参数传 document 或者 window 或者 document.documentElement 即可

 

标签:居中,box,滚动,type,元素,scrollDom,const,document,targetDom
From: https://www.cnblogs.com/wiliam/p/17703378.html

相关文章

  • 【Java入门】交换数组中两个元素的位置
    在Java中,交换数组中的两个元素是基本的数组操作。下面我们将详细介绍如何实现这一操作,以及在实际应用中这种技术的重要性。一、使用场景在编程中,我们经常需要交换数组中的两个元素。例如,当我们需要对数组进行排序或者在某种算法中需要交换元素的位置。这种操作在数据结构、算法、......
  • 【Java入门】交换数组中两个元素的位置
    在Java中,交换数组中的两个元素是基本的数组操作。下面我们将详细介绍如何实现这一操作,以及在实际应用中这种技术的重要性。一、使用场景在编程中,我们经常需要交换数组中的两个元素。例如,当我们需要对数组进行排序或者在某种算法中需要交换元素的位置。这种操作在数据结构、算法......
  • 如果元素中出现中文或空格、制表符、换页符等,则删除转义符或中文并分割
    my_list=['1我是1\r2','2\n\r2我是\s\r我是2','3\s\n3\n\s3']#如果元素中出现中文或空格、制表符、换页符等,则删除转义符或中文并分割,结果如下my_result=[['1','1','2'],['2','2','2'],['3&#......
  • 项目开发中难点-项目使用v-if控制表单/元素/组件显示隐藏,例如调用接口后赋值需重新加
    项目中使用v-if="show"  控制组件的显示或隐藏,当接口返回后this.show=false,进行赋值,后this.show=true显示 。但是页面没有正常显示,此时使用this.$nextTick。 一、$nextTick()概述1.$nextTick()原理$nextTick()是Vue.js框架中的一个方法,它主要用于DOM操作......
  • C#(4):语言基本元素、类型、变量、方法、算法
     穿插算法和数据结构var类型可以根据复制自动推断变量属性    应为get或set访问器:方法名没加括号变量和方法(循环,递归)usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceClassMethodExample{classProgra......
  • android短视频开发,scroll-view的横向滚动
    android短视频开发,scroll-view的横向滚动css .scrollCon{white-space:nowrap;display:flex;align-items:center;}.monthItem{display:inline-block;width:calc(100%/6);font-size:26rpx;color:#3D3D3D;text-align:center;}​总结: 核心css关键点 scroll-view......
  • 直播app开发,CSS3动画实现左右无缝滚动图
    直播app开发,CSS3动画实现左右无缝滚动图<viewclass="shortList_con"><viewclass="scrollCon":style="'width:'+(shortRouteList.length)*210+'rpx'"><viewclass="shortItem"v-for="(item,index......
  • Echarts X轴过长自动滚动 + X轴文字自适应换行
    1.要实现自动滚动option中必须要包含一下内容dataZoom:[{xAxisIndex:0,//这里是从X轴的0刻度开始show:false,//是否显示滑动条,不影响使用type:"slider",//这个dataZoom组件是slider型dataZoom组件startValu......
  • 【动画进阶】当路径动画遇到滚动驱动!
    我的小册 《CSS技术揭秘与实战通关》上线了,想了解更多有趣、进阶、系统化的CSS内容,可以猛击- LINK。本文,我们将一起利用纯CSS,实现如下这么个酷炫的效果:在一年前,我介绍了CSS中非常新奇有趣的一个新特性--@scroll-timeline:革命性创新,动画杀手锏@scroll-timeline。......
  • Leetcode 27. 移除元素
    题目描述给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。双指针Pyth......