我只是在玩jQuery,我在这里遇到了一些问题。正如您在我的示例中所看到的:http://jsfiddle.net/wzdzc/
当您点击“添加div”时,将添加div,并使用正确的类。但是,你不能移动/调整大小?这是为什么?和/或我怎么能够这个?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<style>
#draggable { width: 150px; height: 150px; padding: 0.5em; }
#wrapper { width: 500px; height: 500px; background: red; }
.resize_drag { background-color: white; width: 150px; height: 150px;}
#add_div { padding: 5px; background-color: yellow; width: 200px }
</style>
<script>
$(function() {
var coordinates = function(element) {
element = $(element);
var top = element.position().top;
var left = element.position().left;
$('#results').text('X: ' + left + ' ' + 'Y: ' + top);
}
$(".resize_drag").draggable({
containment: 'parent',
scroll: false,
drag: function() {
var $this = $(this);
var thisPos = $this.position();
var parentPos = $this.parent().position();
var x = thisPos.left - parentPos.left;
var y = thisPos.top - parentPos.top;
$("#results").text(x + ", " + y);
}
});
$( ".resize_drag" ).resizable({
containment: 'parent',
stop: function(event, ui) {
var width = ui.size.width;
var height = ui.size.height;
$("#results2").text(width + ", " + height);
}
});
$("#wrapper").draggable({});
$("#add_div").on("click",function() {
$("<div class='resize_drag'>DragMe</div>").appendTo('#wrapper');
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="resize_drag">
<p>Drag me around</p>
</div>
<div class="resize_drag">
<p>Drag me around2</p>
</div>
</div> <!-- end wrapper -->
<div id="results"></div>
<div id="results2"></div>
<div id="add_div">Add DIV</div>
</body>
</html>
答案 0 :(得分:1)
您需要将resizable
和draggable
函数添加到新元素中,因为$(".resize_drag").draggable()
仅适用于现有元素:
$("#add_div").on("click",function() {
$("<div class='resize_drag'>DragMe</div>").appendTo('#wrapper').draggable().resizable();
});
这是一个简化版本。如果您需要使用参数/事件运行这些函数,也可以将它们添加到单击处理程序中。
答案 1 :(得分:0)
$('.resize_drag').livequery(function() {
$(this).resizable({...});
});
使用http://archive.plugins.jquery.com/project/livequery插件
或者您必须在每个添加的元素上调用$ .resizable
答案 2 :(得分:0)
问题是添加新的div不可拖动和可调整大小的Chenge代码像这样
$("#add_div").on("click",function() {
$("<div class='resize_drag'>DragMe</div>").appendTo('#wrapper').draggable({
containment: 'parent',
scroll: false,
drag: function() {
var $this = $(this);
var thisPos = $this.position();
var parentPos = $this.parent().position();
var x = thisPos.left - parentPos.left;
var y = thisPos.top - parentPos.top;
$("#results").text(x + ", " + y);
}
}).resizable({
containment: 'parent',
stop: function(event, ui) {
var width = ui.size.width;
var height = ui.size.height;
$("#results2").text(width + ", " + height);
}
});
});
});