为什么在左上和左下同时拖动时可调整大小,这给我带来了不想要的行为

时间:2019-06-19 06:50:15

标签: javascript jquery css

我想为div同时应用可调整大小和可拖动属性,并且应将其包含在其父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>

1 个答案:

答案 0 :(得分:2)

诀窍是设置primary div position: relativedraggable div position: 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>