提交 | 用户 | 时间
|
314507
|
1 |
export interface ScrollToParams { |
H |
2 |
el: HTMLElement |
|
3 |
to: number |
|
4 |
position: string |
|
5 |
duration?: number |
|
6 |
callback?: () => void |
|
7 |
} |
|
8 |
|
|
9 |
const easeInOutQuad = (t: number, b: number, c: number, d: number) => { |
|
10 |
t /= d / 2 |
|
11 |
if (t < 1) { |
|
12 |
return (c / 2) * t * t + b |
|
13 |
} |
|
14 |
t-- |
|
15 |
return (-c / 2) * (t * (t - 2) - 1) + b |
|
16 |
} |
|
17 |
const move = (el: HTMLElement, position: string, amount: number) => { |
|
18 |
el[position] = amount |
|
19 |
} |
|
20 |
|
|
21 |
export function useScrollTo({ |
|
22 |
el, |
|
23 |
position = 'scrollLeft', |
|
24 |
to, |
|
25 |
duration = 500, |
|
26 |
callback |
|
27 |
}: ScrollToParams) { |
|
28 |
const isActiveRef = ref(false) |
|
29 |
const start = el[position] |
|
30 |
const change = to - start |
|
31 |
const increment = 20 |
|
32 |
let currentTime = 0 |
|
33 |
|
|
34 |
function animateScroll() { |
|
35 |
if (!unref(isActiveRef)) { |
|
36 |
return |
|
37 |
} |
|
38 |
currentTime += increment |
|
39 |
const val = easeInOutQuad(currentTime, start, change, duration) |
|
40 |
move(el, position, val) |
|
41 |
if (currentTime < duration && unref(isActiveRef)) { |
|
42 |
requestAnimationFrame(animateScroll) |
|
43 |
} else { |
|
44 |
if (callback) { |
|
45 |
callback() |
|
46 |
} |
|
47 |
} |
|
48 |
} |
|
49 |
|
|
50 |
function run() { |
|
51 |
isActiveRef.value = true |
|
52 |
animateScroll() |
|
53 |
} |
|
54 |
|
|
55 |
function stop() { |
|
56 |
isActiveRef.value = false |
|
57 |
} |
|
58 |
|
|
59 |
return { start: run, stop } |
|
60 |
} |