2017-07-26 62 views
2

我有一個代碼添加單擊按鈕時的元素。你如何使預置的元素可拖拽

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

元素無法拖動?爲什麼是這樣?

+0

看看[這個答案](https://stackoverflow.com/questions/22584201/can-inputs-and-textareas-be-draggable「) –

回答

3

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

+0

謝謝!你解決了我的問題,在一個簡單和乾淨辦法。 – Mile

0

你可以做這樣的:

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

這是一個相當複雜的答案,但它的工作原理。注意:我在another answer找到了這個解決方法。