离子事件监听器 on-hold/on-tab Parent/Child 问题

Ionic Event-LIsteners on-hold/on-tab Parent/Child Issue

在一个 cordova/ionic 应用程序中有一个父级 -div 附加了等待侦听器和一个子级 - div 订阅了标签上的事件,就像这样:

<div on-hold="doSomething()">
   <div on-tap="doSomething2()">...</div>
</div>

有时它会起作用,但是当按下时间大于 500 毫秒时,会出现在选项卡上执行而不是暂停的情况。

可以用更好的方式完成吗?请考虑到 child-div 完全填写了 parent 并且应该保持如此。

提前致谢。

当您有另一个 div 的 div 父级时,将传播事件。 你可以在这里自己试试:

.c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
.c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div class="c1" onclick="alert('squareParent');">
  <div class="c2" onclick="alert('squareChild');">
  </div>
</div>

为避免这种情况,您需要停止传播:

document.getElementById("c1").addEventListener('click', function(e) {
  alert("c1");
}, false);

document.getElementById("c2").addEventListener('click', function(e) {
  alert("c2");
  e.stopPropagation();
}, false);
#c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
#c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div id="c1">
  <div id="c2">
  </div>
</div>

如果您需要更多信息,可以查看有关 javascript 泡泡的更多信息。

在尝试了 stopPropagation 之后,我想出了以下答案,需要 setTimeout 来检查 mouse/cursor 是否被保留。

当只点击 child-div(红色)时 doSomething2 会被提醒,而按住 child-div 则会提醒 doSomething parent:

var holding = false;
var secondFunctionCall = false;

document.getElementById("c1").addEventListener('mousedown', function(e) {
 
  holding = true;

  setTimeout(function(){
    if(holding){
      secondFunctionCall = false;
      alert("calling doSomething()");
    }
  },500);

}, false);

document.getElementById("c2").addEventListener('mousedown', function(e) {

  holding = true;
  secondFunctionCall = true;

}, false);

document.getElementById("c2").addEventListener('mouseup', function(e) {

  holding = false;

  if(secondFunctionCall){
    alert("calling doSomething2()");
  }

}, false);
#c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
#c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div id="c1">
  <div id="c2">
  </div>
</div>

将此代码传输到 cordova-app 时,必须将鼠标事件类型替换为已回答的触摸事件类型 here