下拉放大图片实现

先说核心的代码:

1
2
var scale = 1 + Math.abs(scrollY / imgHeight);
imgRef.style.transform = `scale(${scale})`

scrollY是监听滚动的垂直距离,向上滑动scrollY为正,向下拉scrollY为负,推荐配合better-scroll插件进行开发

利用scall,进行scrollY和heigth的占比加上1的值,即可平滑放大

以下为demo代码(配合等比图片实现):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下拉放大图片</title>
<style>
* {
padding: 0;
margin: 0;
}

.container {
height: 300vh;
overflow: hidden;
}

.img-wrapper {
width: 100%;
position: relative;
padding-top: 56.25%;
font-size: 0;
background-image: url('./157b6e43fbf2b2110279cbfcdd8065380dd78ef4.jpg');
background-size: cover;
transform-origin: top;
}
</style>
</head>

<body>
<div class="container">
<div id="img" class="img-wrapper"></div>
</div>
<script>
var imgRef = document.getElementById('img');
document.addEventListener('scroll', (e) => {
var imgHeight = imgRef.clientHeight;
var scrollY = document.documentElement.scrollTop;
var scale = 1 + Math.abs(scrollY / imgHeight);
scale = Math.min(scale, 1.5)
imgRef.style.transform = `scale(${scale})`
})
</script>
</body>

</html>