html和css应如下所示: 当然还有对最新jquery库的引用 jsfiddle link 问题是为什么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>
答案 0 :(得分: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)
});
});
});