【问题标题】:How can I make touch events (on the dom) bubble in javascript?如何在javascript中使触摸事件(在dom上)冒泡?
【发布时间】:2013-09-07 19:33:33
【问题描述】:

在我看来,触摸事件不会冒泡,即使 everyone seems to say or imply that they do 也是如此。我已经在 Chrome 29.0.1547.62(使用“模拟触摸事件”覆盖)和 android webview(使用cordova)上进行了测试,touchstart 事件都没有发生事件冒泡。这是一个例子:

<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <style>
        #a {
            background-color: red;
            position: absolute;
            top: 0px;
            height: 100px;
            width: 100%;
        }
        #b {
            background-color: blue;
            position: absolute;
            top: 0px;
            height: 50px;
            width: 100%;
        }
    </style>
    <script>
        $(function() {
            $('#a').on('touchstart', function(){
                console.log("a start")
            })

            $('#b').on('touchstart', function(){
                console.log("b start")
            })
        })
    </script>
</head>
<body>
<div id="a"></div>
<div id="b"></div>
</body>
</html>

即使 b 位于 a 之上,当 b 被触摸时,也只会触发 b 的 touchstart 事件。怎么回事?

【问题讨论】:

    标签: javascript android jquery cordova touch


    【解决方案1】:

    您不了解事件冒泡。

    这并不意味着偶数会触及所有周围的元素。这意味着事件从嵌套最深的元素一直向上通过其祖先到document,并调用它在途中找到的处理程序。

    在您的 HTML 中,您有兄弟姐妹。

    <div id="a"></div>
    <div id="b"></div>
    

    要使用冒泡,它们需要嵌套。

    <div id="a">
        <div id="b"></div>
    </div>
    

    【讨论】:

    • 顺便说一句,如果你能告诉我如何做我想做的事,我会加分。我必须手动进行元素碰撞计算吗?我希望有更好的方法
    • @BT:我不知道您要完成什么,但一种可能是将您的 "a""b" 元素放入容器中,然后将事件处理程序放在容器。
    • ...哦,您想在触摸点找到所有元素,而不管它们的位置如何?我认为有一些方法可以做到这一点,但我不确定如何。很确定它会涉及document 上的处理程序,然后进行某种分析。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2013-10-22
    • 2017-02-14
    • 2011-08-23
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多