V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
youngPacce
V2EX  ›  前端开发

js 监听问题求助

  •  
  •   youngPacce · 9 天前 · 419 次点击

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

    <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 。

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

    我是在 mousedown 之后才添加 mousemove,mouseup 事件。
    mouseup 之后就会移除掉 mousemove mouseup 事件。
    只需要在 inner 触发 mousedown 的时候阻止冒泡就行了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3258 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 10:50 · PVG 18:50 · LAX 03:50 · JFK 06:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.