javascript - 纯 javascript,onclick 不适用于移动设备

标签 javascript

现在我不是真正的 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";
    }
}

最佳答案

尝试将 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

关于javascript - 纯 javascript,onclick 不适用于移动设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258641/

相关文章:

javascript - 取消选中要执行的元素javascript

javascript - ng-controller 不向浏览器呈现数据

javascript - 如何正确解决jquery冲突

javascript - Ember.Select View 提示传递的值

javascript - 给活跃的 li 元素一个不同的背景

javascript - Jquery 照片上传仅接受 jpeg 不起作用

javascript - 在客户端 Mocha 单元测试期间使用外部类

javascript - 变量未被识别为 JavaScript 中的变量

JavaScript 获取识别按钮点击

javascript - MouseEnter/MouseLeave 事件未正确排队