我有一个网站,我正试图使其在移动设备上也能正常运行。但是,当我分别为 PC 和平板电脑组合 click 和 touchstart 事件时,两者都不起作用(单击事件附加到的元素不会触发)。谁能解释我应该如何解决这个问题?这是一个元素不起作用的示例,笔具有整个项目。
HTML
<div id="menu">
<h1>MENU</h1>
</div>
<div class="dropdown hidden">
<ul>
<li id="home_navlink">Home</li>
<li id="about_navlink">About Me</li>
<li id="work_navlink">My Work</li>
<li id="contact_navlink">Contact Me</li>
</ul>
</div>
JS
let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
if(dropdown.classList.contains("showing")){
dropdown.classList.remove("showing");
dropdown.classList.add("hidden");
}
else{
dropdown.classList.remove("hidden");
dropdown.classList.add("showing");
}
})
最佳答案
使用 javascript 获取菜单:
let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
将处理函数声明为函数引用:
let clickHandler = function() {
if (dropdown.classList.contains("showing")) {
dropdown.classList.remove("showing");
dropdown.classList.add("hidden");
} else {
dropdown.classList.remove("hidden");
dropdown.classList.add("showing");
}
}
将其分配给点击事件:
menu.addEventListener("click", clickHandler);
然后检查触摸事件处理程序并为 touchstart 分配一个函数:
if ('ontouchstart' in window) {
menu.addEventListener("touchstart", function() {
var touchHndl = function() {
//call the clickHandler actually
clickHandler();
//remove the touchend haldler after perform
this.removeEventListener(touchHndl)
}
//attach a handler for touch end when you are in touchstart event
this.addEventListener(touchHndl);
});
}
所以您问的是纯 JavaScript 中的代码段,希望对您有所帮助。 :)
关于javascript - 组合点击和触摸启动事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989705/