gpt4 book ai didi

javascript - Jquery Resizable 不适用于动态创建的 Div

转载 作者:行者123 更新时间:2023-11-30 20:19:55 24 4
gpt4 key购买 nike

我正在动态创建 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>

但是应该注意的是,您使用的是 native 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>

关于javascript - Jquery Resizable 不适用于动态创建的 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com