在屏幕上轻拂元素(HTML5 / JQuery)



我正在尝试创建一些类似"轻弹"的功能。我不只是在屏幕上拖动一个项目,而是想拖动并扔/释放到某个位置。知道如何做到这一点吗?

抱歉,我这里没有任何代码片段...但我只是不知道从哪里开始。

谢谢!--教育部

可以使用鼠标向下、鼠标移动和鼠标向上事件处理程序来获取鼠标事件及其发生的光标位置。您需要在鼠标按下时存储当前光标位置(startCursorPos(和元素位置(startElementPos(。在每个 mousemove 事件中,您可以计算当前光标位置与 startCursorPos 之间的差异,并将结果添加到 startElementPos,并将结果用作新元素位置。这将实现基本的拖放行为。

要获得投掷,您还需要记录鼠标按下和鼠标向上的当前时间。结合位置,您将能够计算移动速度,并在鼠标向上使用它来继续移动一段时间(例如,使用 setInterval(。

var foo=document.getElementById("foo");
var isMoving, startCursorPos, startElementPos, startTime, newPos;
function Point(x,y) {
  this.x=x; this.y=y;
}
Point.fromElement=function(el) {
  return new Point(parseInt(el.style.left), parseInt(el.style.top));
}
Point.sum = function(a,b) {
  return new Point(a.x+b.x, a.y+b.y);
}
Point.difference = function(a,b) {
  return new Point(a.x-b.x, a.y-b.y);
}
Point.prototype.multiply = function(factor) {
  return new Point(this.x*factor, this.y*factor);
}
Point.prototype.distance = function() {
  return Math.sqrt(this.x*this.x + this.y*this.y);
}
Point.prototype.toString = function() {
  return this.x + "x" + this.y;
}
Point.prototype.moveElement = function(el) {
  el.style.left = this.x + "px"; el.style.top = this.y + "px";
}
foo.addEventListener("mousedown", function(e) {
  startCursorPos = new Point(e.pageX, e.pageY);
  startElementPos = Point.fromElement(foo);
  startTime = +new Date();
  isMoving=true;
},false);
window.addEventListener("mousemove", function(e) {
  if (isMoving) {
    var cursorpos = new Point(e.pageX, e.pageY);
    newPos = Point.sum(startElementPos, Point.difference(cursorpos, startCursorPos));
    //console.log(startElementPos, cursorpos, newPos);
    newPos.moveElement(foo);
  }
},false);
window.addEventListener("mouseup", function(e) {
  if (isMoving) {
    isMoving=false;
    var cursorpos = new Point(e.pageX, e.pageY);
    var interval = +new Date() - startTime;
    var movement = Point.difference(cursorpos, startCursorPos).multiply(1/interval);
    var speed = movement.distance();
    console.log(interval, speed, ""+movement);
    moveOn(newPos, movement, speed);
  }
},false);
function moveOn(startPos, movement, speed) {
  startPos = Point.sum(startPos, movement.multiply(speed*200))
  startPos.moveElement(foo);
  if (speed > 10) 
    setTimeout(function() {
      moveOn(startPos, movement, speed/2);
    }, 100);
}
#foo { position:absolute; width:50px;height:50px; background:magenta; }
<div id="foo" style="top:50px; left:50px;"></div>

最新更新