Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

事件冒泡与捕获依赖的是什么? #62

Open
shiiiiiiji opened this issue Sep 1, 2019 · 0 comments
Open

事件冒泡与捕获依赖的是什么? #62

shiiiiiiji opened this issue Sep 1, 2019 · 0 comments
Labels

Comments

@shiiiiiiji
Copy link
Owner

这周在搬砖的过程中,遇到了一个非常基础的问题,虽然后来解决了,但是仔细想想,感觉还是有点不对劲,所以就翻了翻资料,验证下到底是哪里出了问题。

在开发微信小程序的时候,有这样一个结构:

<view class="intro">
  <view class="inner">
    ...
    <view class="block">
      <button bind:touchstart="handleBtn">点击按钮</button>
    </view>
  </view>
  <view class="float"  bind:touchstart="handleFloat">我是浮层</view>
</view>

样式:

.intro {
  text-align: center;
  width: 100%;
  height: 600rpx;
  position: relative;
}
.block{
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #000

}
.float{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

有一个浮层盖在了主要内容的上面,发现button 点击没反应。第一反应过来的就是浮层挡住了,导致button元素上的事件没能触发。那怎样才能既保持这样的结构,又能让事件透传到 button 上呢?

同事尝试性的给出了下面的方案,将浮层放在上面,先画浮层,再画按钮,

<view class="intro">
	<view class="float"  bind:touchstart="handleFloat">我是浮层</view>
  <view class="inner">
   ...
  </view>
</view>

结果真的就 ok 了。然后只能强行解释一波:“是因为后面的元素后面画出来,所以在上面,就先触发了 click”。真的是这样吗?有点刷新我的认知了。

我就在浏览器环境下验证了一番,发现并非如此:正常情况,在这样的结构下,无论浮层在哪里,直接发生在浮层上面的事件无法冒泡到平行节点的子节点上。

所以标题上提出的问题,大家其实都知道,事件冒泡和捕获依赖的是 DOM 树。但为什么还会把这个问题拎出来,是因为在具体开发的时候,真的非常容易把这个和元素的渲染顺序和位置排列混在了一起,进入惯性思维的误区,影响代码实际运行的判断。但和其的确有点关系的是,接收事件的目标节点,也就是事件真实发生的那个节点是否在页面的顶层。

但是,为什么在微信小程序里有这么怪异的表现呢?事实发现,在第二种结构下,button 按钮的确渲染在了浮层的上面。button 也不是原生组件(原生组件文档:native-component | 微信开放文档)。我现在还不是很清楚,具体可以在社区里一起看看微信的人怎么解释。 https://developers.weixin.qq.com/community/develop/doc/00004250b7c4d8d675195b4d65bc00

-EOF-

#技术/文章

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant