我的按钮在移动设备上不起作用,但它在 chrome 上的移动模拟器上起作用

my button isn't working on mobile device but it does works on the mobile simulator on chrome

试图让我的汉堡图标显示移动菜单从隐藏到阻止 "display",代码在桌面上使用 chrome 模拟器工作,但不能在实际的移动设备上工作。 我的网站是 www.rikuzit.co.il

window.onclick = function(event){
    var burger = document.getElementById("burgerIcon");
    var mobileMenu = document.getElementById("mobileMenu");


if(event.target == burger){
    alert("burger was pressed");
        console.log(event.target);
        mobileMenu.style.display = "block"; 
    } else {    
        alert("clicked outside burger");
        console.log(event.target);
        mobileMenu.style.display = "none";
    }
}

我希望点击按钮时会出现菜单。

this answer所示,移动设备最好使用touchstart

window.ontouchstart = function(event){
    var burger = document.getElementById("burgerIcon");
    var mobileMenu = document.getElementById("mobileMenu");


if(event.target == burger){
    alert("burger was pressed");
        console.log(event.target);
        mobileMenu.style.display = "block"; 
    } else {    
        alert("clicked outside burger");
        console.log(event.target);
        mobileMenu.style.display = "none";
    }
}

你可以这样做

window.onclick = eventHandler
window.ontouch = eventHandler


function eventHandler(event){
   ...
}

(复制了 Shubham Chaudhary 的回答) 我希望这能奏效

window.onclick = eventHandler
window.ontouch = eventHandler


function eventHandler(event){
...
}