禁用iOS Safari中的选择上下文菜单

时间:2013-04-16 14:03:11

标签: javascript ios safari webkit

我想禁用在iOS Safari(网络浏览器)中选择某个文字后出现的默认上下文菜单。这可能吗?

context menu destroy

4 个答案:

答案 0 :(得分:3)

有可能,请参阅this example。基本上,重要的是设置正确的css属性:

body { -webkit-touch-callout: none !important; }
a { -webkit-user-select: none !important; }

此外,这里有question解决类似问题

答案 1 :(得分:2)

我找到的唯一方法是删除选择并再次使用javascript选择。 看看我的代码:

/* prevent ios edit-menu */
if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent)) {
    !function(){
        var target = document.body; // the element where the edit menue should be disabled

        var preventSelRecursion;
        document.addEventListener('selectionchange', function(e){
            var S = getSelection();
            if (!S.rangeCount) return;
            if (S.isCollapsed) return;
            var r = S.getRangeAt(0);
            if (!target.contains(r.commonAncestorContainer)) return;
            if (preventSelRecursion) return;
            iosSelMenuPrevent();
        }, false);

        var iosSelMenuPrevent = debounce(function(){
            var S = getSelection();
            var r = S.getRangeAt(0);
            preventSelRecursion = true;
            S = getSelection();
            S.removeAllRanges();
            setTimeout(function(){ // make remove-add-selection removes the menu
                S.addRange(r);
                setTimeout(function(){
                    preventSelRecursion = false;
                });
            },4);
        },800); // if no selectionchange during 800ms : remove the menu

        /* helper-function */
        function debounce(fn, delay) {
            var timer = null;
            return function () {
                var context = this, args = arguments;
                clearTimeout(timer);
                timer = setTimeout(function () {
                    fn.apply(context, args);
                }, delay);
            };
        }
    }();
}

答案 2 :(得分:0)

根据onclick blocks copy+paste on Mobile Safari?,如果文本位于具有onclick事件的元素中,则不会显示上下文菜单。

答案 3 :(得分:0)

受汉斯·古斯塔夫森(Hans Gustavson)的回答启发,我提出了TypeScript中更简单的解决方案:

function disableIosSafariCallout(this: Window, event: any) {
  const s = this.getSelection();
  if ((s?.rangeCount || 0) > 0) {
    const r = s?.getRangeAt(0);
    s?.removeAllRanges();
    setTimeout(() => {
      s?.addRange(r!);
    }, 50);
  }
}
document.ontouchend = disableIosSafariCallout.bind(window);

此解决方案实际上是一种解决方法。选择文本时,您可能仍会看到文本选择标注显示,然后立即消失。我不确定汉斯·古斯塔夫森的答案是否有相同的缺陷...

相关问题