【问题标题】:Click outside an element not working on tablet and phone单击无法在平板电脑和手机上运行的元素外部
【发布时间】:2016-07-14 15:00:34
【问题描述】:

我在我的页面上放置了一个脚本,以在用户单击屏幕上的任意位置时隐藏具有特定类的所有元素。 该代码在 PC 上完美运行,但不适用于平板电脑和手机。我应该只使用 Javascript,而不是 jQuery。

<script type="text/javascript">
    function onClick(id) {
        var e = document.getElementById(id);
        if(e.className == 'item active') {
            e.className = 'item none';
        }
        else {  
            var x = document.querySelectorAll('.item.active');
            for(var i = 0; i < x.length; i++){
                x[i].className = "item none";
            }
            e.className = 'item active';            
        }
    }

    function findClosest (element, fn) {
        if (!element) return undefined;
        return fn(element) ? element : findClosest(element.parentElement, fn);
    }
    document.addEventListener("click", function(event) {

        if (document.querySelector('.item.active') != null){        
            var t = document.querySelector('.item.active').id;  
        }

        var target = findClosest(event.target, function(el) {
            return el.id == t;
        });
        if (!target) {
            var x = document.querySelectorAll('.item.active');
            for(var i = 0; i < x.length; i++){
                x[i].className = "item none";
            }
        }
    }, false);

</script>

<div id="item1" class="item none" onclick="onClick('item1')">
    ...
</div>

<div id="item2" class="item none" onclick="onClick('item2')">
    ...
</div>  

...

【问题讨论】:

  • 您是否在使用某种 JavaScript 触摸事件库来覆盖常规计算机鼠标事件?
  • @KevBot 不,费德里科是对的。我只使用了点击事件,没有使用触摸。

标签: javascript tablet


【解决方案1】:

单击事件在 PC 上有效,因为它与鼠标单击相关联。但是,在桌子和电话上,没有点击事件。相反,您应该使用触摸事件。试试这个:

document.addEventListener("touchstart", function(event) {
      // Click outside logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    相关资源
    最近更新 更多