纯JavaScript,在移动设备上无法使用onclick事件。

3

我并不是Javascript方面的专家,但是我似乎遇到了移动设备上onclick函数普遍存在的问题。Onclick需要鼠标操作,而在手机上这并不适用。在Jquery中,你可以使用"on"函数来解决这个问题,但是在普通的Javascript中该怎么做呢?

// Get the modal
var modal = document.getElementById('reserveer-modal');

// Get the button that opens the modal
var btn = document.getElementById("reserveer-knop");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    var x = window.innerWidth;
    if (x > 768) {

        //event.preventDefault();
        modal.style.display = "block";
    } else {
        //event.preventDefault();
    }
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

1
您可以使用touchstart事件,根据MDN文档,“当触摸点放置在触摸表面上时,将触发touchstart事件。” https://developer.mozilla.org/en-US/docs/Web/Events/touchstart - 例如,使用方式为 el.addEventListener("touchstart", handleStart) - Dan
4个回答

4
尝试将 onclick 更改为 addEventListener,看是否有帮助。

// When the user clicks the button, open the modal 
btn.addEventListener('click', function () {
    var x = window.innerWidth;
    if (x > 768) {
        //event.preventDefault();
        modal.style.display = "block";
    } else {
        //event.preventDefault();
    }
});

您也可以将命名函数传递给addEventListener

1
将点击事件监听器绑定到元素上应该可以解决你一直遇到的问题。
btn.addEventListener("click", function() {
    var x = window.innerWidth;
    if (x > 768) {
        //event.preventDefault();
        modal.style.display = "block";
    } else {
        //event.preventDefault();
    }
});

另外一种选择是使用touchstart事件,它与“mousedown”事件一样,只是针对移动设备。

elem.addEventListener("touchstart", handler);

您的代码将如下所示:

Your code would look like this:

btn.addEventListener("touchstart", function() {
    var x = window.innerWidth;
    if (x > 768) {
        //event.preventDefault();
        modal.style.display = "block";
    } else {
        //event.preventDefault();
    }
});

3
他应该监听 click 而不是 touchstart。监听 touchstart 会影响拖动操作,比如说。 - German Latorre

0

我曾遇到同样的问题,将z-index设置为100后问题解决了。 在我的情况下,似乎是因为z-index存在问题。


1
这与此处的问题无关。 - andres.gtz

0

请确保您的代码中没有任何async/await函数或箭头函数() => {}。移动浏览器似乎使用介绍async/await或箭头函数之前的较旧版本的JavaScript。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接