代码如下
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<style>
.draggable { width: 200px; height: 200px; border: 1px dotted #000 }
</style>
<script>
$(function() {
$( ".draggable" ).draggable();
$("#add_elem").click(function(){
$elem = '<div class="draggable">方框B</div>';
$('body').append($elem);
});
});
</script>
</head>
<body>
<button id="add_elem">添加元素</button>
<div class="draggable">
<p>方框A</p>
</div>
</body>
</html>效果图如下:
如图中:
方块A可以拖拽,这个可以理解,但是当点击添加元素按钮生成方块B后,方块B不可以拖拽,这是为什么?有什么办法可以实现对方块B的拖拽?
= =必然不能。。 .draggable()是主动调用 才会在elem上添加额外的class才能达到拖拽效果。
$(function() { $( ".draggable" ).draggable(); $("#add_elem").click(function(){ elem = $('<div/>').addClass('draggable').text('方框'); elem.draggable(); $('body').append(elem); }); });jsfiddle:http://jsfiddle.net/77Dj2/3381/