用uniapp的uni.requireNativePlugin('bindingx')插件 写一个拖动页面
时间: 2024-02-06 16:08:53 浏览: 32
好的,可以参考下面的代码实现一个简单的拖动页面:
1. 在页面中添加一个可拖动的元素,如下:
```html
<template>
<view class="drag-elem" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
<text>拖我</text>
</view>
</template>
```
2. 在`<script>`中,引入`bindingx`插件,然后实现拖动逻辑:
```javascript
<script>
export default {
methods: {
onTouchStart(e) {
// 记录初始触摸点
this.startX = e.touches[0].pageX;
this.startY = e.touches[0].pageY;
// 获取当前元素的位置
const rect = uni.createSelectorQuery().select('.drag-elem').boundingClientRect();
rect.exec((res) => {
this.elemX = res[0].left;
this.elemY = res[0].top;
});
},
onTouchMove(e) {
// 计算拖动距离
const moveX = e.touches[0].pageX - this.startX;
const moveY = e.touches[0].pageY - this.startY;
// 更新元素位置
uni.requireNativePlugin('bindingx').bind({
eventType: 'timing',
element: document.querySelector('.drag-elem'),
props: [
{
element: '.drag-elem',
property: 'transform.translateX',
expression: `${this.elemX + moveX}px`
},
{
element: '.drag-elem',
property: 'transform.translateY',
expression: `${this.elemY + moveY}px`
}
]
});
},
onTouchEnd() {
// 解除绑定
uni.requireNativePlugin('bindingx').unbind({
eventType: 'timing',
element: document.querySelector('.drag-elem')
});
}
}
};
</script>
```
3. 样式部分,可以根据需求自行调整:
```css
<style>
.drag-elem {
position: absolute;
left: 100px;
top: 100px;
width: 100px;
height: 100px;
background-color: #f00;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
user-select: none;
touch-action: none;
}
</style>
```
这样就可以实现一个简单的拖动页面了。需要注意的是,`bindingx`插件需要在真机上才能生效。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)