我正在动态创建div,并将它们设置为可拖动和可调整大小。可拖动的效果很好,但可调整大小的效果不好。我不知道为什么。这是我的代码:
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>
答案 0 :(得分:1)
代码可以正常工作,您只是没有包括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>