How to make a div or object gradually move to poin

2019-05-19 03:56发布

问题:

So I have an object or div that is a square 10x10 pixels. I want to be able to click somewhere in the browser window that causes the div to gradually move towards the point I clicked.

回答1:

$(document).click(function(event) {
    $('#divID').css({
       'position': 'absolute', 
       'left': event.clientX + document.body.scrollLeft, 
       'top': event.clientY + document.body.scrollTop });
});

Demo



回答2:

jQuery

$(document).click(function(event) {
    var x = event.pageX,
        y = event.pageY;

    $('div').animate({
        top: y,
        left: x
    }, 1000);
});

CSS

div {
    background: red;
    padding: 5px;
    position: absolute; 
}

HTML

<div>hello</div>

jsFiddle.



回答3:

jQuery code

$("body").bind("click", function(e){
  var str = "( " + e.pageX + ", " + e.pageY + " )";
  $("span").text("Clicked  at " + str);
});

after getting this you need to update your div.style.left and div.style.top !