I have to move a div by clicking on it, clicking again I must stop the div in that position. Now the problem is: when I want to move again the div, does not activate the mousemove event ... how can I fix it?

$('.move_div').live('click', function() {                    
    $('html').on('mousemove', function(e) {
       var x = e.pageX - this.offsetLeft;
       var y = e.pageY - this.offsetTop;
       $('div').css({'top': y, 'left': x});
    });
    $("html").live('click', function() {
       $('html').off('mousemove');
    });
});
有帮助吗?

解决方案

var ele = '.move_adv';
var moveBool = false;

$(function () {
    $('html').on('mousemove', function (e) {
        console.log($(this).width());
        if (moveBool == true) {
            var x = e.pageX - $(ele).width()/2;
            var y = e.pageY - $(ele).height()/2;
            $(ele).css({
                'top': y,
                    'left': x
            });
        }
    });
});

$(ele).live('click', function () {
    moveBool = !moveBool;
});

http://jsfiddle.net/6y24s/2/

The main logic is storing the 'moveability' state of the div in a boolean.

You would also like to refine the code more.

其他提示

Fiddle here , if you want to keep your code then only thing you need to add is

event.stopPropagation();

When you click on the div the mousemove handler is added to the div. Then an event handler is added to the document that removes any mousemove event handlers.
You then move the mouse and the div follows, you click and the mousemove handler is deleted. You click on the div again, a mousemove event handler is added, though then the click event handler from the document takes away the mousemove handler.
So whenever you click after the first two clicks the mousemove handler is simultaneously created and destroyed.

Also use .on() instead of .live()
.live() was deprecated in JQuery 1.7

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top