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

使用 rxjs 实现一个简易拖拽元素功能 #419

Open
JounQin opened this issue Feb 18, 2022 · 0 comments
Open

使用 rxjs 实现一个简易拖拽元素功能 #419

JounQin opened this issue Feb 18, 2022 · 0 comments
Labels

Comments

@JounQin
Copy link
Owner

JounQin commented Feb 18, 2022

const { fromEvent, map, switchMap, takeUntil } = rxjs

const mousedown$ = fromEvent(document.getElementById('drag'), 'mousedown')
const mousemove$ = fromEvent(document, 'mousemove')
const mouseup$ = fromEvent(document, 'mouseup')

mousedown$
  .pipe(
    switchMap(downEv => {
      const startX = downEv.clientX
      const startY = downEv.clientY
      const originalLeft = +drag.style.left.replace('px', '')
      const originalTop = +drag.style.top.replace('px', '')
      return mousemove$.pipe(
        map(moveEv => {
          const moveX = moveEv.clientX
          const moveY = moveEv.clientY
          const deltaX = moveX - startX
          const deltaY = moveY - startY
          return {
            originalLeft,
            originalTop,
            deltaX,
            deltaY,
          }
        }),
        takeUntil(mouseup$), // `takeUntil` 不能移到外面,否则触发一次 `mouseup` 后整个流就终止了
      )
    }),
  )
  .subscribe(({ originalLeft, originalTop, deltaX, deltaY }) => {
    drag.style.left = originalLeft + deltaX + 'px'
    drag.style.top = originalTop + deltaY + 'px'
  })

https://jsfiddle.net/rj5odeh6/24/

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