gpt4 book ai didi

javascript - jQuery 添加 div 但无法移动/调整大小

转载 作者:行者123 更新时间:2023-11-28 02:27:40 26 4
gpt4 key购买 nike

我只是在玩 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>

最佳答案

您需要将 ressizeddraggable 函数添加到新元素,因为 $(".resize_drag").draggable()仅适用于现有的:

   $("#add_div").on("click",function() {
$("<div class='resize_drag'>DragMe</div>").appendTo('#wrapper').draggable().resizable();
});

fiddle

这是一个简化版本。如果您需要使用参数/事件运行这些函数,请将它们也添加到点击处理程序中。

关于javascript - jQuery 添加 div 但无法移动/调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662778/

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