fix: 修复Taro环境下拖拽功能的getBoundingClientRect错误
� 问题修复:
- 替换getBoundingClientRect()为Taro.createSelectorQuery()
- 使用Taro官方推荐的boundingClientRect()方法获取元素位置
- 解决小程序环境下DOM API不可用的问题
� 技术改进:
- 异步获取容器位置信息并缓存
- 在触摸开始时预先获取容器数据
- 保持拖拽过程中的流畅性和响应性
- 完全兼容微信小程序环境
✅ 功能验证:
- 项目成功构建,无编译错误
- 保持所有原有拖拽功能特性
- 维持10%-90%拖拽范围限制
- 确保触摸事件正常响应
现在可以在微信开发者工具中正常使用拖拽分割线功能
This commit is contained in:
parent
a0efbc2cbd
commit
3647b40631
|
|
@ -1,5 +1,6 @@
|
|||
import { View, Text, Image } from '@tarojs/components'
|
||||
import { useState, useRef } from 'react'
|
||||
import Taro from '@tarojs/taro'
|
||||
import { Template } from '../../store/types'
|
||||
import './index.css'
|
||||
|
||||
|
|
@ -11,6 +12,7 @@ interface TemplateCardProps {
|
|||
export default function TemplateCard({ template, onClick }: TemplateCardProps) {
|
||||
const [splitPosition, setSplitPosition] = useState(50) // 分割线位置百分比
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [containerInfo, setContainerInfo] = useState<any>(null)
|
||||
const containerRef = useRef<any>(null)
|
||||
|
||||
const handleClick = () => {
|
||||
|
|
@ -19,29 +21,38 @@ export default function TemplateCard({ template, onClick }: TemplateCardProps) {
|
|||
}
|
||||
}
|
||||
|
||||
// 获取容器信息
|
||||
const getContainerInfo = () => {
|
||||
return new Promise((resolve) => {
|
||||
const query = Taro.createSelectorQuery()
|
||||
query.select('.merged-image-container').boundingClientRect((rect) => {
|
||||
if (rect) {
|
||||
setContainerInfo(rect)
|
||||
resolve(rect)
|
||||
}
|
||||
}).exec()
|
||||
})
|
||||
}
|
||||
|
||||
// 处理触摸开始
|
||||
const handleTouchStart = (e: any) => {
|
||||
const handleTouchStart = async (e: any) => {
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
// 获取容器信息用于后续计算
|
||||
await getContainerInfo()
|
||||
}
|
||||
|
||||
// 处理触摸移动
|
||||
const handleTouchMove = (e: any) => {
|
||||
if (!isDragging) return
|
||||
if (!isDragging || !containerInfo) return
|
||||
e.stopPropagation()
|
||||
|
||||
const touch = e.touches[0]
|
||||
const container = containerRef.current
|
||||
if (!container || !touch) return
|
||||
|
||||
// 获取容器的位置信息
|
||||
const rect = container.getBoundingClientRect()
|
||||
const containerLeft = rect.left
|
||||
const containerWidth = rect.width
|
||||
if (!touch) return
|
||||
|
||||
// 计算触摸点相对于容器的位置
|
||||
const touchX = touch.clientX - containerLeft
|
||||
const percentage = Math.max(10, Math.min(90, (touchX / containerWidth) * 100))
|
||||
const touchX = touch.clientX - containerInfo.left
|
||||
const percentage = Math.max(10, Math.min(90, (touchX / containerInfo.width) * 100))
|
||||
|
||||
setSplitPosition(percentage)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue