jQuery mousemove with CSS translate

时间:2015-11-09 08:30:53

标签: jquery html css

我想在屏幕中移动对象并为该对象分配CSS规则。我试过这样:

var pos = {};
var isMoving = false;
var zoomScale = 1;

$(".box").on("mousedown", function(e) {
    pos = { 
        x: e.pageX, 
        y: e.pageY 
    };    
    isMoving = true;
}).on("mouseup", function(){
    isMoving = false;
}).on("mousemove", function(e){       
    if (isMoving) {
        $(".box").css({
            "transform": "translate(" + ((e.pageX - pos.x) * zoomScale) + "px, " + ((e.pageY - pos.y) * zoomScale) + "px)"
        });
    }
});

当我再次尝试移动时,不知何故,物体移动的位置比我预期的要小一些。

1 个答案:

答案 0 :(得分:-1)

var clicked = false;
$(".box").mousedown(function(){
    clicked = true;
});
$(".box").mousemove(function(event){
    if (clicked){
    $(".box").css({
               //whatever css here and you can use event.pageX, event.pageY
               //to detech mouse position and event.clientX, event.clientY
                });
    }
});

<强> UPDATE ::

var clicked = false;
var pos = {};
var zoomScale = 1;
$(".box").mouseup(function(event) {
  console.log(clicked);
  clicked = false;
    pos = {
    x: event.pageX,
    y: event.pageY
  };
});
$(".box").mousedown(function(event) {
  clicked = true;
  pos = {
    x: event.pageX,
    y: event.pageY
  };
});
$(".box").mousemove(function(event) {
  console.log(pos);
  if (clicked) {
    $(".box").css({
      "transform": "translate(" + ((event.pageX-($(".box").width()/2) ) * zoomScale) + "px, " + ((event.pageY-($(".box").height()/2)) * zoomScale) + "px)"
    });
  }
});

CODEPEN