javascript - 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>
解决方案
代码工作正常,你只是没有包含 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>
推荐阅读
- typescript - 启动应用程序时打字稿抛出错误
- python - 基于通用 x 轴值对数据框柱形图进行分组
- angular - 离子/角度离开页面事件
- reactjs - React Router V4 使用 Material UI 在 ListItem 中实现 NavLink
- python-3.x - 将数组拆分为数组数组python
- c - 为什么我不能以这种方式复制终止的 null ?
- sql - 如何查找没有子节点的树节点
- excel - 表格多列Excel中最常见的值
- react-native - addImageFromBase64 的使用
- javascript - 在 JavaScript 中将 Uint8Array 转换为 Float64Array