简体   繁体   中英

maintaining relative screen size of jquery ui draggable/resizable object on window resize

I have a web page with a couple div elements that are resizable and draggable through the jquery ui library.

$('#myDiv').draggable({ containment: "parent" }).resizable({ aspectRatio: true});

Dragging and resizing work fine, but I would like the divs to resize to maintain their relative size to the window as the window is resized. For example if drag div 1 to the top right and size it to 50% of the screen width, is there a way to maintain that sizing as the window resizes? I can't seem to find any options within jquery or jquery ui to allow me to force the elements to size based on percentage. Is there a way to do this with jquery, or do I need to write code that gets called on window resize that can handle this?

What I have done is following the answer of this question:

stackoverflow.com/questions/37328053/draggable-object-goes-outside-the-container-when-the-window-is-resized

What they propose is on stop the dragging event, convert to % positions you would like to keep, in the above exeample I converted left and top.

    $('#myDiv').draggable({containment: "parent",  
        stop: function(e, ui) { 
              var percLeft = ui.position.left/ui.helper.parent().width()*100;
              var percTop = ui.position.top/ui.helper.parent().height()*100;
              ui.helper.css('left', percLeft + '%');      
              ui.helper.css('top', percTop + '%');    
              }
       }).resizable({ aspectRatio: true});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM