离子事件-支架处于保留/选项卡上父/子问题

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

本文关键字:选项 问题 保留 -支 事件 于保留      更新时间:2023-09-26

在 cordova/ionic 应用程序中,有一个附加了保持侦听器的父div 和一个订阅了选项卡上事件的子div,如下所示:

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

它有时会起作用,但是当按下时间大于 500 毫秒时,会出现执行 on-tab 而不是保持的情况。

这能以更好的方式完成吗?请注意,child-div 完全填写了父级,并且应该保持如此。

提前谢谢。

当您有一个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 bubble的信息。

在尝试了 stopPropagation 之后,我想出了以下答案,需要 setTimeout 来检查鼠标/光标是否被按住。

当只是点击子div(红色) doSomething2 时,就会发出警报,而按住 child-div 提醒 doSomething of 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 鼠标时,事件类型必须替换为触摸事件类型,因为此处已回答。