2

我有一个应该在它的父级中移动的目标,在该父级中单击该父级。

一些小提琴:http: //jsfiddle.net/GmerZ/

一些HTML:

<div id="rControl">
  <p>R1 / R2</p>
  <div class="widget">
    <div class="target"></div>
  </div>
</div>

一些通过 CoffeeScript 的 jQuery:

rControl = $('#rControl')
widget = rControl.find '.widget'
target = rControl.find '.target'

clicked = no
widget
  .mousedown =>
    clicked = yes

  .mouseup =>
    clicked = no

  .mousemove (e) =>
    if clicked
      target.css
        top:  "#{e.offsetY}px"
        left: "#{e.offsetX}px"

问题是您拖动时目标会抖动。好像是第一个事件把widget放在了光标下,第二个事件发生在target而不是widget背景上,所以现在偏移量是相对于target,而不是父widget,offset值很多更小。目标现在错误地移动到小部件的左上角。

显然,目标应该处理这些事件,也不应该根据目标的位置提供点击位置信息。

.widget无论鼠标是否在.target?

另外,我很乐意这样做,而无需重新排列 HTML 以强制目标在小部件下,我必须缺少一些棘手的事件委托魔术。

4

1 回答 1

1

Just filter out mousemove calls to only act on the ones fired by widget:

Updated JS (just one small change to the mousemove if):

rControl = $('#rControl')
widget = rControl.find '.widget'
target = rControl.find '.target'

clicked = no
widget
  .mousedown =>
    clicked = yes

  .mouseup =>
    clicked = no

  .mousemove (e) =>
    if clicked and e.target == widget[0]
      target.css
        top:  "#{e.offsetY}px"
        left: "#{e.offsetX}px"

See on jsfiddle.

于 2013-05-13T08:01:11.950 回答