[英]How do you make prepended elements draggable
I have a code that adds elements upon the click of a button. 我有一个代码,单击按钮即可添加元素。
$(document).ready(function(){ $("#add_txt").click(function(){ $("body").prepend('<input class="style_txt">'); }); }); //However when I add... $( function() { $( ".style_txt" ).draggable(); } );
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <button class="btn" id="add_txt">Add Text</button>
The element can not be dragged? 元素不能拖动? Why is this?
为什么是这样?
you can't do it with input
element, wrap it inside span 你不能用
input
元素做到这一点,包裹在跨度
$(document).ready(function() { $("#add_txt").click(function() { $("body").prepend('<span><input class="style_txt"></span>'); $(".style_txt").parent().draggable(); }); });
span { padding: 5px; border: 1px solid #eee; cursor: move; }
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <button class="btn" id="add_txt">Add Text</button>
You could do it like this: 您可以这样做:
$(document).ready(function() { $("#add_txt").click(function() { $("body").prepend('<div class="style_text"><input /></div>'); $(".style_text").draggable({ start: function(event, ui) { $(this).data("preventBehaviour", true); } }); $(".style_text :input") .on("mousedown", function(e) { var mdown = document.createEvent("MouseEvents"); mdown.initMouseEvent( "mousedown", true, true, window, 0, e.screenX, e.screenY, e.clientX, e.clientY, true, false, false, true, 0, null ); $(this).closest(".style_text")[0].dispatchEvent(mdown); }) .on("click", function(e) { var $draggable = $(this).closest(".style_text"); if ($draggable.data("preventBehaviour")) { e.preventDefault(); $draggable.data("preventBehaviour", false); } }); }); });
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <button class="btn" id="add_txt">Add Text</button>
It's a rather complex answer, but it works. 这是一个相当复杂的答案,但确实有效。 Note: I found this workaround in another answer .
注意:我在另一个答案中找到了此解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.