js 监听问题求助

12 天前
 youngPacce

现在有两个块,结构如下:

<div id = "outer" style = "width:50px;height:50px;">
	<span id = "inner" style = "positon:absolute;buttom:0;right:0;width:5px;height:5px;">
	
	</span>
</div>

如图: https://mjj.today/i/TXCM5H 这两个块都监听了mousedown,mousemove,mouseup

我想实现的功能

点击 outer 可以移动整个块,点击 inner 拖动可以控制 outer 块的宽高。

现状

如果我拖拽 inner 的话,outer 会在增加宽高的同时移动。

尝试过

增加一个状态控制 outer 不进行处理,但是无法实现两个功能同时存在。

这种情况有什么好的处理办法吗?用的原生的 js 。

463 次点击
所在节点    前端开发
7 条回复
johnnyNg
12 天前
mouse 事件里面有 eventtarget 吧,判断一下 target 是 outer 还是 inner
johnnyNg
12 天前
还有一种方案,在各个事件里面阻止一下事件冒泡
youngPacce
12 天前
@johnnyNg 尝试过,但是 target 在移动的过程中貌似会冒泡传递出去,导致这个 target 最终不准确,还是用不了。我倒是没尝试过阻止事件冒泡,我去了解一下。
zhtyytg
11 天前
肯定要阻止事件冒泡的,前端常识
yanyiming
11 天前
在 inner 的事件处理器中给事件对象增加一个属性,比如 fromInner: true ,因为事件对象是会传递到 outer 的,所以 outer 也能获取这个属性值。然后根据属性值判断逻辑即可。
youngPacce
11 天前
@yanyiming j 具体怎么处理呢? e.target 还是 e.frominner? 另外我的 mousemove 和 mouseup 都是加在 ducoment 上的,似乎到了 mousemove 再判断 target 就不太好使了。
youngPacce
11 天前
解决了,这里说一下我的解决方案,

我是在 mousedown 之后才添加 mousemove,mouseup 事件。
mouseup 之后就会移除掉 mousemove mouseup 事件。
只需要在 inner 触发 mousedown 的时候阻止冒泡就行了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1050089

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX