基于
svelte3.x
构建轻量级自定义pc端虚拟滚动条组件SvelteScrollbar。支持原生滚动条、自动隐藏、垂直+水平滚动、自定义尺寸/颜色及间隔
等功能。
在lib目录下新建Scrollbar组件文件夹。
引入插件
import Scrollbar from '$lib/Scrollbar'
svelte-layer 一款svelte3自定义网页版弹窗组件
如上图:支持垂直+水平两种滚动模式,另外水平滚动条还支持滚轮滑动。
使用插件
使用<Scrollbar></Scrollbar>
包裹住内容区,即可快速创建一个虚拟化滚动条区域。
<!-- //原生滚动条 --><Scrollbar native><div>自定义内容信息。</div></Scrollbar><!-- //自动隐藏滚动条 --><Scrollbar autohide={true}><div>自定义内容信息。</div></Scrollbar><!-- //水平滚动条(支持滚轮滑动) --><Scrollbar mousewheel><div>自定义内容信息。</div></Scrollbar><!-- //自定义高度/最大高度 --><Scrollbar height="200" maxHeight="350"><div>自定义内容信息。</div></Scrollbar><!-- //自定义大小/间隙/颜色 --><Scrollbar size="10px" gap="5" color="#09f"><div>自定义内容信息。</div></Scrollbar>
自定义参数
svelteScrollbar组件支持如下自定义参数配置。
<script>// 是否开启原生滚动条export let native = false// 是否自动隐藏滚动条export let autohide = false// 滚动条尺寸export let size = undefined// 滚动条颜色export let color = ''// 滚动条层叠export let zIndex = null// 滚动条区域高度export let height = undefined// 滚动条区域最大高度export let maxHeight = undefined// 滚动条间隙export let gap = 0// 是否开启水平滚轮滚动控制export let mousewheel = false...</script>
<div class="vui__scrollbar" bind:this={el} on:mouseenter={handleMouseEnter} on:mouseleave={handleMouseLeave}><div class="vscroll__wrap" class:hidenative={!bool(native)} bind:this={wrap} on:scroll={handleScroll} on:mousewheel={handleMouseWheel} style="{wrapStyle}"><slot /></div><div class="vscroll__bar vertical" class:ishide={!data.isShowBar} on:mousedown={e => handleClickTrack(e, 0)} ><div class="vscroll__thumb" bind:this={barY} style="background: {color}; height: {data.barHeight}px; width: {addUnit(size)}" on:mousedown={e => handleDragThumb(e, 0)}></div></div><div class="vscroll__bar horizontal" class:ishide={!data.isShowBar} on:mousedown={e => handleClickTrack(e, 1)}><div class="vscroll__thumb" bind:this={barX} style="background: {color}; width: {data.barWidth}px; height: {addUnit(size)}" on:mousedown={e => handleDragThumb(e, 1)}></div></div></div>
js核心逻辑处理部分。
<script>/*** @Descsvelte3自定义美化滚动条svelte-scrollbar* @Timeandy by -05* @About Q:282310962 wx:xy190310*/// ...import {onMount, afterUpdate, createEventDispatcher, tick } from 'svelte'const dispatch = createEventDispatcher()import util from './util'$: data = {// 滚动条宽度barWidth: 0,// 滚动条高度barHeight: 0,// 滚动条水平偏移率ratioX: 1,// 滚动条垂直偏移率ratioY: 1,// 鼠标是否按住滚动条isTaped: false,// 鼠标是否悬停于滚动区域isHover: false,// 显示滚动条isShowBar: !bool(autohide)}const bool = (boolean) => JSON.parse(boolean) ? true : falseconst addUnit = (val) => val ? parseInt(val) + 'px' : nulllet observeTimer = nulllet c = {}// 滚动条对象let ellet wraplet barXlet barY$: wrapStyle = `height: ${addUnit(height)}; max-height: ${addUnit(maxHeight)}`$: GAP = addUnit(gap)onMount(() => {console.log('监听滚动条开启...')updated()let observer = new MutationObserver(mutation => {updated()})observer.observe(wrap, {attributes: true,childList: true,subtree: true,attributeFilter: ['style', 'class']})window.addEventListener('resize', util.throttle(updated))return () => {observer.disconnect()window.removeEventListener('resize', updated)console.log('监听滚动条关闭...')}})afterUpdate(() => {// console.log('监听dom更新...')})// 鼠标滑入function handleMouseEnter() {data.isHover = truedata.isShowBar = trueupdated()}// 鼠标滑出function handleMouseLeave() {data.isHover = falseif(!data.isTaped && bool(autohide)) {data.isShowBar = false}}// 拖动滚动条function handleDragThumb(e, index) {// ...}// 点击滚动条插槽function handleClickTrack(e, index) {if(index == 0) {wrap.scrollTop = (Math.abs(e.target.getBoundingClientRect().top - e.clientY) - barY.offsetHeight / 2) * data.ratioYbarY.style.transform = `translateY(${wrap.scrollTop / data.ratioY}px)`}else {wrap.scrollLeft = (Math.abs(e.target.getBoundingClientRect().left - e.clientX) - barX.offsetWidth / 2) * data.ratioXbarX.style.transform = `translateX(${wrap.scrollLeft / data.ratioX}px)`}}// 更新滚动区async function updated() {// ...}// 鼠标滚动事件function handleScroll(e) {let target = e.targetlet statusif(target.scrollTop == 0) {status = 'top' // 滚动至顶部}else if(target.scrollTop + target.offsetHeight >= target.scrollHeight) {status = 'bottom' // 滚动至底部}/*** 父组件调用 const { target, status, scrollTop, scrollLeft } = e.detail*/dispatch('scroll', {target, // 滚动对象status, // 滚动状态(记录滚动位置)scrollTop: target.scrollTop,scrollLeft: target.scrollLeft})updated()}// 控制滚轮水平滚动function handleMouseWheel(e) {if(!bool(mousewheel)) returne.preventDefault()if(wrap.scrollWidth > wrap.offsetWidth) {wrap.scrollLeft += e.deltaY}}// 滚动到一组特定坐标export async function scrollTo(arg1, arg2) {await tick()if(typeof arg1 == 'object') {wrap.scrollTo(arg1)}else if(!isNaN(arg1) && !isNaN(arg2)) {wrap.scrollTo(arg1, arg2)}}// 设置滚动条到顶部的距离export async function setScrollTop(value) {await tick()wrap.scrollTop = value == 'top' ? 0 : value == 'bottom' ? wrap.scrollHeight : parseInt(value)barY.style.transform = `translateY(${wrap.scrollTop / data.ratioY}px)`}// 设置滚动条到左边的距离export async function setScrollLeft(value) {await tick()wrap.scrollLeft = value == 'left' ? 0 : value == 'right' ? wrap.scrollWidth : parseInt(value)barX.style.transform = `translateX(${wrap.scrollLeft / data.ratioX}px)`}</script><style>@import 'Scrollbar.scss';</style>
如上图:支持滚动到指定位置及监听scroll滚动事件。
<Scrollbar on:scroll={handleScroll}><div>滚动条内容。</div></Scrollbar><script>// 监听滚动事件function handleScroll(e) {const {target, status, scrollTop, scrollLeft } = e.detailscrollTopVal = scrollTopscrollLeftVal = scrollLeft// 判断滚动状态(方法1)/*if(scrollTop == 0) {scrollStatus = '滚动至顶部'}else if(scrollTop + target.offsetHeight >= target.scrollHeight) {scrollStatus = '滚动底部'}else {scrollStatus = '滚动中'}*/// // 判断滚动状态(方法2)if(status == 'top') {scrollStatus = '滚动至顶部'}else if(status == 'bottom') {scrollStatus = '滚动底部'}else {scrollStatus = '滚动中'}}</script>
ok,基于svelte3开发自定义虚拟化滚动条就分享这么多。后续还会分享一些svelte实例项目。
最后附加一个svelte3仿微信APP实例聊天项目
/yanxinyun1990/article/details/124004427
如果觉得《svelte-scrollbar: 基于svelte.js自定义滚动条组件|svelte3虚拟滚动条》对你有帮助,请点赞、收藏,并留下你的观点哦!