首页 > 解决方案 > 如何防止 iOS Safari 做出不需要的选择?

问题描述

当我在 iOS Safari 中长按我的 React 应用程序上的工具栏按钮时,它会选择图标。我用工具栏上的 CSS 禁用了它:

-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;

但随后 Safari 继续选择它可以找到的下一个愚蠢的元素。

因此,我最终将样式应用于我的应用程序的根目录,但现在用户当然不能在段落等内容中选择任何文本。

我真正想要的是一种设置屏障的方法,上面写着“Safari,你能停止尝试选择你可能找到的下一个东西吗?”

所以在我的工具栏组件上我这样做了,我验证它被调用了:

  onTouchStart={e => {
    e.stopPropagation();
    e.preventDefault();
    e.bubbles = false;
  }}

我也试过这个:

  onTouchStartCapture={e => {
    e.stopPropagation();
    e.preventDefault();
    e.bubbles = false;
  }}

与 ,onSelect相同onSelectCapture

然而 Safari 忽略了所有这些,并继续选择层次结构一直到根 DIV,直到它发现一些无意义的选择。当我通过复制查看它选择的内容时,它只是一个空格。

我错过了什么?我真的必须应用user-select: none;到根目录,然后有选择地允许在有意义的地方进行选择,例如在包含文本的 DIV 上吗?然后,长按工具栏时,Safari 怎么会找不到并选择它?

标签: javascriptreactjsdommobile-safarireact-dom

解决方案


您可以应用以下 css,因此您仍然可以选择<p><h>标记:

p {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h1 {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h2 {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h3 {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h4 {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h5 {
 -webkit-user-select: text !important;
 user-select: text !important;
}
h6 {
 -webkit-user-select: text !important;
 user-select: text !important;
}

推荐阅读