Javascript 在iOS safari中禁用选择上下文菜单
我想禁用在iOS Safari(web浏览器)中选择特定文本后出现的默认上下文菜单。可能吗 这是可能的,请参阅。基本上,重要的部分是设置正确的css属性:Javascript 在iOS safari中禁用选择上下文菜单,javascript,ios,safari,webkit,Javascript,Ios,Safari,Webkit,我想禁用在iOS Safari(web浏览器)中选择特定文本后出现的默认上下文菜单。可能吗 这是可能的,请参阅。基本上,重要的部分是设置正确的css属性: body { -webkit-touch-callout: none !important; } a { -webkit-user-select: none !important; } 另外,这里有一个解决类似问题的方法,根据,如果文本位于具有onclick事件的元素中,上下文菜单将不会显示。我找到的唯一方法是删除选择并使用javascri
body { -webkit-touch-callout: none !important; }
a { -webkit-user-select: none !important; }
另外,这里有一个解决类似问题的方法,根据,如果文本位于具有onclick事件的元素中,上下文菜单将不会显示。我找到的唯一方法是删除选择并使用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);
};
}
}();
}
受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);
此解决方案实际上是一种变通方法。选择文字时,可能仍会看到文字选择标注显示,然后立即消失。我不确定Hans Gustavson的答案是否也有同样的缺陷…你是说在Safari Web浏览器中还是在应用程序的UIWebView中?Web浏览器,编辑的问题我见过这种解决方案,但它没有禁用文本选择菜单,只有长按链接时出现的长按菜单:(实际上,它甚至不可选择,这可能不是您想要的。