关于SortableJS在handle模式下移动端无法拖拽的解决办法

原因

个人项目使用到了这个库,PC操作好好的,移动端一看不行,然后去官方github-issues查看搜mobile的issue,发现大家也会这样。找了一圈看了下,应该是handle(句柄)模式下,库没有做事件监听导致的。

解决办法

要么换个库,要么在移动端的时候,取消句柄模式即可。

const wrapper: HTMLElement = document.querySelector(
  ".el-checkbox-group>.el-space"
);

const config: Sortable.Options = {
  animation: 300,
  handle: ".drag-btn",
  onEnd: ({ newIndex, oldIndex, item }) => {
    // ...
  },
};

if (isMobile) {
  // 这个不知道有没有用,待测试
  config.touchStartThreshold = 100;
  // 移动端不支持handle
  delete config.handle;
}
Sortable.create(wrapper, config);

PS:判断是否在移动端可以参考下列方法

要判断项目是否在移动端打开,可以利用浏览器的 User Agent(用户代理)来判断。用户代理是浏览器发送给服务器的一串字符串,它包含了关于浏览器和操作系统的信息。

在 Vue.js 3 中,可以使用 window.navigator.userAgent 获取当前浏览器的用户代理字符串。然后,你可以使用正则表达式或现有的库来判断用户代理字符串是否表示移动设备。

以下是一个示例,使用正则表达式来判断用户代理字符串是否表示移动设备:

这个正则表达式匹配了一些常见的移动设备的关键词,如果用户代理字符串中包含其中之一,就会被判断为移动设备。

const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(window.navigator.userAgent);

或者可以使用这个:(🌟推荐🌟,无需安装其他包)

const isMobile = () => {
  let userAgent = navigator.userAgent.toLowerCase();
  let isMidp = userAgent.match(/midp/i) == "midp";
  let isUcweb = userAgent.match(/ucweb/i) == "ucweb";
  let isAndroid = userAgent.match(/android/i) == "android";
  let isIOS = userAgent.match(/iphone os/i) == "iphone os";
  let isWindowsCE = userAgent.match(/windows ce/i) == "windows ce";
  let isRV1234 = userAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
  let isWindowsMobile = userAgent.match(/windows mobile/i) == "windows mobile";
  return isMidp || isUcweb || isAndroid || isIOS || isWindowsCE || isRV1234 || isWindowsMobile;
};

此外,Vue.js 3 本身并没有提供专门用于判断移动设备的库。不过,你可以使用一些第三方库,如 mobile-detect,它提供了更全面的移动设备检测功能。

安装 mobile-detect

npm install mobile-detect

在 Vue.js 3 项目中使用 mobile-detect

import MobileDetect from 'mobile-detect';

// 创建 MobileDetect 实例
const md = new MobileDetect(window.navigator.userAgent);

// 判断是否为移动设备
const isMobile = md.mobile() !== null;

这样,你就可以使用 isMobile 变量来判断项目是否在移动端打开了。

posted @ 2024-01-30 13:56  脆皮鸡  阅读(545)  评论(0)    收藏  举报