0

html 和 csss 应该如下所示:当然还有对最新 jquery 库 jsfiddle 链接 问题的引用,为什么 mousemove 事件不会关闭?

<style>
#ball{
  position : absolute;
  padding : 0px;
  top:0px;
}​
</style>
<img id="ball" src="http://javascript.info/files/tutorial/browser/events/ball.gif"/>
<div id="debug"></div>​




<script>
        var xp = 0,
            yp = 0;
   > when mouse is down we start listen to mousemove
        $(document).on("mousedown", "#ball", function(e) {
            $(document).on("mousemove", this, function(e) {
                mouseX = e.pageX - 20;
                mouseY = e.pageY - 20;
                xp += (mouseX - xp) / 22;
                yp += (mouseY - yp) / 22;
                $("#ball").css({
                    left: xp,
                    top: yp
                });
    > when mouse is up we stop listen to mouse move
            }).on("mouseup", "#ball", function(e) {
                $(document).off("mousemove",this, function(e) {
                });
            })
        })​
</script>
4

1 回答 1

0
var xp = 0,
    yp = 0;
var dragging = false;
$("#ball").on("mousedown", function(e) {
    dragging = true;
    $(document).on("mousemove", this, function(e) {
        if(dragging) {
            mouseX = e.pageX - 20;
            mouseY = e.pageY - 20;
            xp += (mouseX - xp) / 12;
            yp += (mouseY - yp) / 12;
             $("#ball").css({
                left: xp,
                top: yp
            });
        }
    });
    $(document).on("mouseup", function(e) {
        dragging = false;
        $(document).off("mousemove",this, function(e) {
            alert(e.pageX)
        });
    });

});
于 2012-04-17T22:03:58.027 回答