繁体   English   中英

如何使前置元素可拖动

[英]How do you make prepended elements draggable

我有一个代码,单击按钮即可添加元素。

 $(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> 

元素不能拖动? 为什么是这样?

你不能用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> 

您可以这样做:

 $(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> 

这是一个相当复杂的答案,但确实有效。 注意:我在另一个答案中找到了此解决方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM