i get left and top postion of div but i getting wrong value when top going to negative value then the result showing is wrong. and same as left. what is i do wrong this code.
$('#mega-game').draggable( { drag: function(){ var offset = $(this).offset(); var xPos = offset.left; var yPos = offset.top; $('#mega-p-x').text('x: ' + xPos); $('#mega-p-y').text('y: ' + yPos); $('.man').css('top', yPos + 'px'); $('.man').css('left', xPos + 'px'); } });
#mega-game { width: 6em; height: 6em; padding: 0.5em; border: 3px solid #ccc; border-radius: 0 1em 1em 1em; } .man{ width: 2em; height: 2em; background:red; position:relative; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="mega-game"> <ul> <li id="mega-px"></li> <li id="mega-py"></li> </ul> </div> <div class="man"></div>
I guess .offset()
method get position of the element with a little delay or drag
event is triggered before position is changed. You should take position values from arguments of drag
callback. Check out fixed code snippet:
$('#mega-game').draggable( { drag: function(e, ui){ var offset = $(this).offset(); var xPos = ui.position.left; var yPos = ui.position.top; $('#mega-p-x').text('x: ' + xPos); $('#mega-p-y').text('y: ' + yPos); $('.man').css('top', yPos + 'px'); $('.man').css('left', xPos + 'px'); } });
#mega-game { width: 6em; height: 6em; padding: 0.5em; border: 3px solid #ccc; border-radius: 0 1em 1em 1em; } .man{ width: 2em; height: 2em; background:red; position:relative; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="mega-game"> <ul> <li id="mega-px"></li> <li id="mega-py"></li> </ul> </div> <div class="man"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.