javascript - 使 onclick 在 iphone 上工作

标签 javascript

我一直在我的 javascript 中使用“onclick”,但现在我希望它也能在 Iphone 上运行。对于支持 ontouchstart 的设备,是否有一种简单的方法可以使所有“onclick”像 ontouchstart 一样工作?

或者我是否需要将所有脚本编写两次(一个使用 onclick,一个使用 ontouchstart)? :S

注意:我不想使用 jquery 或任何其他库。

<!DOCTYPE html>
<title>li:hover dropdown menu on mobile devices</title>
<script>
window.onload = function () {
    if ('ontouchstart' in window) {
        // all "onclick" should work like "ontouchstart" instead
    }
    document.getElementById('hbs').onclick = function () {
        alert('element was clicked');
    }
}
</script>
<a id=id1 href=#>button</a>

最佳答案

这篇文章得到了更多的关注,所以我要添加另一个常用的、更新的技巧:

// First we check if you support touch, otherwise it's click:
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';

// Then we bind via thát event. This way we only bind one event, instead of the two as below
document.getElementById('hbs').addEventListener(touchEvent, someFunction);

// or if you use jQuery:
$('#hbs').on(touchEvent, someFunction);

let touchEvent 应该在您的 javascript 顶部被声明为失效(也不在 document.ready 中)。这样你就可以在你所有的 javascript 中使用它。这也允许简单的 (jQuery) 使用。


旧答案:

这解决了复制代码的需要(至少是最低限度)。不确定是否可以组合它们

function someFunction() {
    alert('element was clicked');
}

document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;

document.getElementById('hbs')
    .addEventListener('click', someFunction)
    .addEventListener('touchstart', someFunction);

关于javascript - 使 onclick 在 iphone 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914568/

相关文章:

javascript - SAPUI5 View 表被切断

javascript - 如何将 $scope 对象获取到 Angular 服务

javascript - 返回 localStorage 数组中的最后一个元素

javascript禁用单个单选按钮

javascript - Backbone : Singleton views?

javascript - 在 sagas 中使用回调函数

javascript - 在 rails 中,如何 g-zip 由 'javascript_include_tag' 生成的组合 javascript 文件?

javascript - HTML/CSS "Pop-Up"窗口和禁用背景

javascript - 如何在 CasperJS onWaitTimeout 事件处理程序中回显缺少的选择器?

javascript - 验证复选框限制javascript