0

我正在尝试使用具有可拖动 div 的 Framer Motion 设置组件,但拖动目标(可拖动元素)是可拖动父 div 的子级。与操作系统窗口类似,只能由顶部菜单栏拖动。我摆弄了dragControls,但我不知道这是否是我的答案。如果我将 motion.div 设置为子 div,则只有它会移动。

         <motion.div drag > // This entire div should move when the target is dragged
            <div> // I only want this div to be the draggable target
                <span>DRAG ME</span>
            </div>
            <div>
                <p>This div should move with the parent draggable div, but you can not drag from this div.</p>
            </div>
        </motion.div>
4

2 回答 2

1

这是我的解决方案,使用dragListenerprop(没有很好的文档记录):

import {motion, useDragControls} from 'framer-motion'

export function Example() {
  const dragControls = useDragControls()

  return (
    <motion.div
      drag
      dragControls={dragControls}
      dragListener={false}
    >
      <div
        onPointerDown={(e) => {
          dragControls.start(e)
        }}
      >
        <span>DRAG ME</span>
      </div>

      <div>
        <p>
          This div should move with the parent draggable div, but you can not drag from this div.
        </p>
      </div>
    </motion.div>
  )
}

这里有一个代码沙盒演示:https ://codesandbox.io/s/focused-dawn-p4whg?file=/src/App.tsx:0-617

于 2021-07-13T10:21:39.600 回答
0

不幸的是,目前没有简单的方法可以做到这一点。这个小“hack”可能是唯一的方法:(你是对的,将需要dragControls)

import { motion, useDragControls } from "framer-motion";

export const Example = () => {
  const dragControls = useDragControls();

  function onDragStart(e, info) {
    // We will ignore the request to drag if it's not coming from the handle
    if (!e.target.classList.contains( 'drag-handle' ) ) {
    
      // Stop the drag - `e` and `info` are needed from the library
      dragControls.componentControls.forEach( entry => {
        entry.stop( e, info )
      })
    }
  }

return (
  // Add dragControls and onDragStart to the div you want to be draggable
  <motion.div
    drag
    dragControls={dragControls}
    onDragStart={onDragStart}
  >
    <div>
      {* Add a descriptive class to the element that enables the dragging *}
      <span className="drag-handle">DRAG ME</span>
    </div>
    <div>
      <p>This div should move with the parent draggable div, but you can not drag from 
      this div.</p>
    </div>
  </motion.div>
)

}

于 2021-01-11T16:23:33.287 回答