【问题标题】:jQuery touch eventsjQuery 触摸事件
【发布时间】:2015-08-28 11:36:47
【问题描述】:

如何管理触摸事件。当我在不同的元素上编写几个 touchstart 时,它们都同时被激活,我无法将它们分开。 您能否帮助我了解如何在没有第三方库的情况下正确管理它们。 如果有提示或小教程,我将不胜感激。

$(".content").on("touchstart", function(){$(this).stop().animate({top: '-50px'}, 600);});

【问题讨论】:

  • 实际上无法回答您的问题。您是否有父/子触摸事件的问题。
  • 我无法触及元素。例如,这两个函数是同时重新形成的,尽管它们是针对不同的元素确定的。 $('.main').on('touchstart', function() { $('.main').stop().animate({top: '0px'}, 600, 'easeOutBounce'); });第二个事件$('.content').on('touchstart', function() { $('.content').stop().animate({top: '-50px'}, 600, 'easeOutBounce'); });
  • 所以我猜:.main 是包含.content 正确的容器。
  • 是的,.main 中的 .content <div class="main"> <div class="content"></div> </div>

标签: jquery jquery-mobile touch touch-event


【解决方案1】:

根据您的问题,event 在 dom 树上冒泡。这意味着如果您触发任何绑定在子元素上的事件并且相同的事件也应用于父元素,那么发生在子元素上的任何事件都将爬上父元素并且执行相同的事件。

所以我建议你使用event.stopPropagation(); 并在回调函数中传递event:

$('.main').on('touchstart', function() { 
     $('.main').stop().animate({top: '0px'}, 600, 'easeOutBounce'); 
}); 

$('.content').on('touchstart', function(event) { 
    event.stopPropagation();
    $('.content').stop().animate({top: '-50px'}, 600, 'easeOutBounce'); 
});

看看下面的演示,使用click事件。

$('.main').click(function(){
    alert(this.className + ' clicked.');
});

$('.content').click(function(event){
    //event.stopPropagation();
    alert(this.className + ' clicked.');
});


// you can enable the commented line and see the effect.
.main{border:solid 1px green; padding:20px;}
.content{border:solid 1px red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main"> parent<br><br><div class="content">child</div> </div>

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多