Flying div to another div

jsfiddle link .
I want the mousedown event to fire on #flyingDiv , I can move it around #holder , when mouseup and mouse leave #holer , I can't move it. In my code, sometimes #flyingDiv is located next to the black frame when I move the mouse in the center of #holder .
HTML:

 <div id="holder" style="position: relative; margin: 20px auto; border: 1px solid black; width: 400px !important; height: 400px !important;"> <div id="flyingDiv" style="position: absolute; background-color: green; width: 10px !important; height: 10px !important; left: 195px; top: 195px;"></div> </div> 

Javascript:

 $(function(){ var fd = $("#flyingDiv"); $("#flyingDiv").bind("mousedown", function(event) { $(this).attr("pressed", true); }); $("#holder").bind("mouseup", function(event) { $("#flyingDiv").removeAttr("pressed"); }); $("#holder").bind("mousemove", function(event) { var div = $("#flyingDiv"); if (div.attr("pressed")) { var width = div.width(); if (event.offsetX >= width / 2 && ($(this).width() - event.offsetX) >= width / 2) { div.css("left", parseInt(event.offsetX - width / 2) + "px"); } var height = div.height(); if (event.offsetY >= height / 2 && ($(this).height() - event.offsetY) >= width / 2) { div.css("top", parseInt(event.offsetY - height / 2) + "px"); } } }); }); 

UPD
I found that if event.eventPhase == 3 is an old event. Link
But still, the code does not work fast.

+4
source share
2 answers

I can replicate the issue in Chrome, and this seems like a performance issue; the mouse move event fires very quickly, and the execution of both DOM requests and recording on each event will force the slow client at some points where the style will not get a value for the top and left for several frames, and this will be the default 0.

You might want to think about optimized solutions like jQuery draggable , since you are already using jQuery.

+2
source

Do not use bind, use $ (element) .mousedown (). mouseup ()

maybe something like this ... http://jsfiddle.net/KQpe9/

  $(function() { $('.slider').slider(); }); $.fn.slider = function() { return this.each(function() { var $el = $(this); $el.css('top', 0); var dragging = false; var startY = 0; var startT = 0; $el.mousedown(function(ev) { dragging = true; startY = ev.clientY; startT = $el.css('top'); }); $(window).mousemove(function(ev) { if (dragging) { // calculate new top var newTop = parseInt(startT) + (ev.clientY - startY); //stay in parent var maxTop = $el.parent().height()-$el.height(); newTop = newTop<0?0:newTop>maxTop?maxTop:newTop; $el.css('top', newTop ); } }).mouseup(function() { dragging = false; }); }); } 
+1
source

Source: https://habr.com/ru/post/1495721/


All Articles