首页 > 解决方案 > 为什么在左上角和左下角的可拖动同时应用时可调整大小给我一个不需要的行为

问题描述

我想同时为 div 应用 resizable 和 draggable ,它应该包含在其父 div 中,但是在向左或上角拖动并从西北、西、西南手柄调整它的大小时,会使 div 没有宽度。

  <!DOCTYPE html>
     <html>    
         <head>
               <title>Resizable</title>

             <script src="https://code.jquery.com/jquery-1.12.4.js"> 
             </script>
             <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"> 
      </script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

       <style type = "text/css">      

              #primary
             {
               width : 30rem;
               height : 30rem;
              background-color:green;
              margin: auto;  
            }
             #draggable{
                width: 15rem;
                height: 15rem;
                 background-color: yellow;



                  }
             .ui-widget-content{
                  background: yellow;
              }


        </style>
      </head>
      <body>


           <div id = "primary">

           <div id= "draggable" class="ui-widget-content">
           </div>             
           </div>




        <script >
             w= parseInt($('#draggable').css('width'),10);
             h= parseInt($('#draggable').css('height'),10);
             $( function() {
                    $( "#draggable" ).resizable( {handles: 'ne , nw ,se, 
       sw , n ,e ,s,w', minWidth : w, minHeight : h ,containment:"parent" 
       }).draggable({containment: "parent"});
        } );

     </script>
   </body>
  </html>

标签: javascriptjquerycss

解决方案


诀窍是设置primarydivposition: relativedraggabledivposition: absolute

$(document).ready(function(){
	let w = parseInt($('#draggable').width());
	let h = parseInt($('#draggable').height());
  
  $( function() {
    $( "#draggable" ).resizable( 
    {
      handles: 'n, e, s, w, ne, se, sw, nw', 
      minWidth : w, 
      minHeight : h,
      containment:"#primary" 
    }).draggable(
    {
    	containment: "#primary",
     });
});

});
#primary
{
  width: 30rem;
  height: 30rem;
  background-color: green;
  margin: auto;
  position: relative !important;
}

#draggable{
  width: 15rem;
  height: 15rem;
  background-color: yellow;
  position: absolute !important;
}

.ui-widget-content{
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id = "primary">

      <div id= "draggable" class="ui-widget-content">
      </div>             
    </div>


推荐阅读