2017-10-08 74 views
1

我需要繪製簡單的圓形並使用mouseup,mousedown和mousemove事件移動它們。jquery創建圈子,讓他們移動

我工作中的代碼如下:

$(document).ready(function(){ 
 

 
    $(document).on('mousedown','#wrapper, .circle',function(e){ 
 
    var elem = $(this); 
 

 
    if(elem.hasClass('circle')){ 
 
     e.stopPropagation(); 
 
     var x = e.pageX; 
 
     var y = e.pageY; 
 
     var r = 20; 
 
     elem.css({'top':y-r,'left':x-r}); 
 
     elem.addClass('target'); 
 
     $('#wrapper').on('mousemove',function(f){ 
 
     var x = f.pageX; 
 
     var y = f.pageY; 
 
     var r = 20; 
 
     elem.css({'top':y-r,'left':x-r}); 
 
     }); 
 
    } 
 
    else{ 
 
     var punto = $('<div></div>').addClass('circle target'); 
 
     var x = e.pageX; 
 
     var y = e.pageY; 
 
     var r = 20; 
 

 
     $(this).append(punto); 
 
     punto.css({'top':y-r,'left':x-r}); 
 

 
     $('#wrapper').on('mousemove',function(e){ 
 
     var x = e.pageX; 
 
     var y = e.pageY; 
 
     var r = 20; 
 
     $('.target').css({'top':y-r,'left':x-r}); 
 
     }); 
 
    } 
 
    }); 
 

 
    $(document).on('mouseup','.target',function(e){ 
 
    var x = e.pageX; 
 
    var y = e.pageY; 
 
    var r = 20; 
 
    $(this).css({'top':y-r,'left':x-r}); 
 
    $('.target').removeClass('target').off('mousemove'); 
 
    }); 
 

 

 

 

 

 
});
#wrapper { 
 
\t display:inline-block; 
 
\t position:relative; 
 
\t border:1px solid black; 
 
\t width:500px; 
 
\t height: 500px; 
 
\t margin-right:10px; 
 
} 
 

 
.circle { 
 
\t border:1px solid red; 
 
\t border-radius:50%; 
 
\t width:20px; 
 
\t height:20px; 
 
\t position: absolute; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="wrapper"></div>

我有一些問題讓代碼正常工作。我可以通過mousedown/mouseup事件或mousedown-movemouse-mouseup將紅色圓圈放入屏幕中。 但是,一旦放置了一個圓並且我想移動它,我就會鼠標移動,鼠標移動或鼠標移動鼠標和鼠標移動,並且該圓與鼠標一起移動,但它永遠不會再放置在包裝中。

請幫忙嗎?

非常感謝你提前。

回答

0

我終於把它與jQuery的用戶界面。

function enableMovement(){ 
    $('.circle').draggable(); 
} 

$(document).on('mousedown','#wrapper',function(e){ 
    var circle = $('<div></div>').addClass('circle target'); 
    var x = e.pageX; 
    var y = e.pageY; 
    var r = 20; 

    $(this).append(circle); 
    circle.css({'top':y-r,'left':x-r}); 
    enableMovement(); 
}); 

$(document).on('mousedown','.circle',function(e){ 
    e.stopPropagation(); 
}); 

$(document).on('mousemove','#wrapper, .circle',function(e){ 
    var x = e.pageX; 
    var y = e.pageY; 
    var r = 20; 
    $('.target').css({'top':y-r,'left':x-r}); 
}); 

$(document).on('mouseup','.target',function(e){ 
    var x = e.pageX; 
    var y = e.pageY; 
    var r = 20; 
    $('.target').css({'top':y-r,'left':x-r}); 
    $('.target').removeClass('target').off('mousemove'); 
});