功能简介
将小程序中指定的模块,使用手指放大或者缩小。
定义需要放大缩小的模块
<template>
<view class="container">
<view id="content" class="content" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"
:style="{'transform-origin':`${originX}px ${originY}px` ,'transform': `scale(${lastScale})`}">
<view>文本内容</view>
<view>文本内容</view>
<view>文本内容</view>
<view>文本内容</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
originX: 0,
originY: 0,
lastDistance: 0,
lastScale: 1,
};
},
methods: {
onTouchStart(event) {
if (event.touches.length === 2) {
const point1 = event.touches[0];
const point2 = event.touches[1];
this.lastDistance = this.getDistance(point1, point2);
const query = wx.createSelectorQuery();
query.select('#content').boundingClientRect((rect) => {
this.originX = (point1.clientX + point2.clientX) / 2 - rect.left;
this.originY = (point1.clientY + point2.clientY) / 2 - rect.top;
}).exec();
}
},
onTouchMove(event) {
if (event.touches.length === 2) {
const point1 = event.touches[0];
const point2 = event.touches[1];
const distance = this.getDistance(point1, point2);
const scale = distance / this.lastDistance;
this.lastDistance = distance;
this.lastScale *= scale;
if(this.lastScale < 1){
this.lastScale = 1
}
}
},
onTouchEnd() {
this.lastDistance = 0;
this.lastScale = 1;
},
getDistance(point1, point2) {
const x = point2.clientX - point1.clientX;
const y = point2.clientY - point1.clientY;
return Math.sqrt(x * x + y * y);
},
},
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
overflow: auto;
padding-top: 200rpx;
}
.content {
width: 100%;
height: 100%;
background-color: #eee;
transition: transform 0.3s;
}
</style>