首页 > 解决方案 > Jquery Resizeable 不适用于动态创建的 Div

问题描述

我正在动态创建 div,并将它们设置为可拖动和可调整大小。Draggable 工作得很好,但 resizeable 不行。我不知道为什么。这是我的代码:

function creatediv() {
  var div = document.createElement('div');
  div.className = "draggable resizable";
  div.innerHTML = "You can drag this, but you cannot Resize!! ";
  div.style.position = 'absolute';
  div.style.border = "medium solid black";
  div.style.width = "250px";
  document.getElementById("bdy").appendChild(div);
  $(".draggable").draggable({
    snap: true
  }); //have to call this to activate the jquery draggable effects on the newly created div.
  $(".resizable").resizable();
}
<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>
<button onclick="creatediv()">Create new element !</button>
<div id="bdy"></div>

标签: javascriptjquery

解决方案


代码工作正常,你只是没有包含 jQueryUI 的样式表来使它工作:

function creatediv() {
  var div = document.createElement('div');
  div.className = "draggable resizable";
  div.innerHTML = "You can drag this, but you cannot Resize!! ";
  div.style.position = 'absolute';
  div.style.border = "medium solid black";
  div.style.width = "250px";
  document.getElementById("bdy").appendChild(div);
  
  $(".draggable").draggable({
    snap: true
  });
  
  $(".resizable").resizable();
}
<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>

<!-- Add this \/ -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button onclick="creatediv()">Create new element !</button>
<div id="bdy"></div>

但是应该注意的是,您使用的是原生 JS 方法和 jQuery 的奇怪组合。如果您要承受加载 jQuery 的惩罚,那么使用其简洁的方法是有意义的。这是上面的逻辑翻译成jQuery:

$('.create').click(function() {
  var $div = $('<div />', {
    'class': 'draggable resizable foo',
    'text': 'You can drag and resize this!'
  }).appendTo('#bdy').draggable({
    snap: true
  }).resizable();
});
.foo {
  position: absolute;
  border: medium solid black;
  width: 250px;
} 
<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="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button class="create">Create new element !</button>
<div id="bdy"></div>


推荐阅读