dragging items based on percentage to containment element

Deadly 提交于 2019-11-29 03:26:36

I've found a solution;

$( ".item" ).draggable({
  containment: ".door",
  stop: function( event, ui ) {
   $(this).css("left",parseInt($(this).css("left")) / ($(".door").width() / 100)+"%");
   $(this).css("top",parseInt($(this).css("top")) / ($(".door").height() / 100)+"%");
  }
});
user3629322

Try this Code :

$( ".element" ).draggable({

    stop: function (){
     var l = ( 100 * parseFloat($(this).css("left")) / parseFloat($(this).parent().css("width")) )+ "%" ;
     var t = ( 100 * parseFloat($(this).css("top")) / parseFloat($(this).parent().css("height")) )+ "%" ;
     $(this).css("left" , l);
     $(this).css("top" , t);
     }

});

Little bit updated version of all above:

$('.element').draggable({
    containment: 'parent',
    stop: function( event, ui ) {
        var $elm = $(this);
        var pos = $elm.position(),
            parentSizes = {
                height: $elm.parent().height(),
                width: $elm.parent().width()
            };

        $elm.css('top', ((pos.top/parentSizes.height) * 100) + '%').css('left', ((pos.left/parentSizes.width) * 100) + '%');
}});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!