[英]Disable selection context menu in iOS safari
我想禁用在 iOS Safari(網絡瀏覽器)中選擇特定文本后出現的默認上下文菜單。 那可能嗎?
我發現的唯一方法是刪除選擇並使用 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);
};
}
}();
}
根據onclick 阻止在 Mobile Safari 上復制+粘貼? , 如果文本位於具有 onclick 事件的元素中,則不會顯示上下文菜單。
受到 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);
此解決方案實際上是一種解決方法。 當您選擇一個文本時,您可能仍會看到文本選擇標注顯示然后立即消失。 我不確定漢斯·古斯塔夫森的回答是否有同樣的缺陷......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.