元素属性 | 说明 |
---|---|
clientWidth | 获取元素可视部分的宽度,即 CSS 的 width 和 padding 属性值之和,元素边框和滚动条不包括在内,也不包含任何可能的滚动区域。 |
clientHeight | 获取元素可视部分的高度,即 CSS 的 height 和 padding 属性值之和,元素边框和滚动条不包括在内,也不包含任何可能的滚动区域。 |
offsetWidth | 元素在页面中占据的宽度总和,包括 width、padding、border 以及滚动条的宽度。 |
offsetHeight | 只读属性,返回该元素的像素高度,高度包含该元素的垂直内边距和边框,且是一个整数。 |
scrollWidth | 只读属性,是元素内容宽度的一种度量,括由于溢出导致的视图中不可见内容。 |
scrollHeight | 只读属性,是一个元素内容高度的度量,包括由于溢出导致的视图中不可见内容。 |
scrollTop | 可以获取或设置一个元素的内容垂直滚动的像素数。 |
scrollLeft | 可以读取或设置元素滚动条到元素左边的距离。 |
一、横向滚动:
// HTML
<div ref="xxxRef"></div>
<button @click="onScroll('left')"></button>
<button @click="onScroll('right')"></button>
// JS
import { ref, nextTick } from 'vue'
const xxxRef = ref(null)
const onScroll = (type) => {
nextTick(() => {
const distance = type === 'left' ? 0 : xxxRef.value.scrollWidth;
xxxRef.value.scrollLeft = distance
})
}
二、竖向滚动:
// HTML
<div ref="xxxRef"></div>
<button @click="onScroll('top')"></button>
<button @click="onScroll('bottom')"></button>
// JS
import { ref, nextTick } from 'vue'
const xxxRef = ref(null)
const onScroll = (type) => {
nextTick(() => {
const distance = type === 'top' ? 0 : xxxRef.value.scrollHeight;
xxxRef.value.scrollTop = distance
})
}
最后,为了使滚动变得跟德芙一样丝滑,还得加个css样式:
div {
scroll-behavior: smooth;
}