2011-12-24 13 views
0

jqueryプラグインを使用してドラッグ可能なオブジェクトを作成しています。jqueryで新しく作成されたオブジェクトの既存の設定を継承する方法は?

プラグインはhereで、デモはhereです。

$('.drag') 
    .live("click", function(){ 
     $(this).toggleClass("selected"); 
    }) 
    .drag("init",function(){ 
     if ($(this).is('.selected')) 
      return $('.selected');      
    }) 
    .drag("start",function(ev, dd){ 
     dd.attr = $(ev.target).attr("className"); 
     dd.width = $(this).width(); 
     dd.height = $(this).height(); 
     dd.limit = $div.offset(); 
     dd.limit.bottom = dd.limit.top + $div.outerHeight() - $(this).outerHeight(); 
     dd.limit.right = dd.limit.left + $div.outerWidth() - $(this).outerWidth(); 
    }) 
    .drag(function(ev, dd){ 
     var props = {}; 
     if (dd.attr.indexOf("E") > -1){ 
      props.width = Math.round(Math.max(32, dd.width + dd.deltaX)/ 20) * 20; 
     } 
     if (dd.attr.indexOf("S") > -1){ 
      props.height = Math.round(Math.max(32, dd.height + dd.deltaY)/ 20) * 20; 
     } 
     if (dd.attr.indexOf("drag") > -1){ 
      props.top = Math.round(Math.min(dd.limit.bottom, Math.max(dd.limit.top, dd.offsetY))/ 20) * 20; 
      props.left = Math.round(Math.min(dd.limit.right, Math.max(dd.limit.left, dd.offsetX))/ 20) * 20; 
     } 
     $(this).css(props); 
}); 

それは複雑に見えるかもしれないが、しかしそれはないすべては、いくつかのドラッグ可能なdiv要素のHORを行い、このhtnl:

<input type="button" id="add" value="Add a Box" /> 
<div class="test" id="container"> 


<div class="drag" style="left:100px;"> 
    <div class="handle SE"></div> 
</div> 
<div class="drag" style="left:180px;"> 
    <div class="handle SE"></div> 
</div> 

</div> 

もjsfiddleと私のテストスクリプトは、このことから始まるhere

です

ボタンを使用していくつかのvidsを追加します:

var $div = $('#container'); 
var num = 1; 
    $('#add').click(function(){ 
     $('<div class="handle SE"><div class="drag" style="left:20px;"/>') 
      .text(num++) 
      .appendTo(document.body) 
      .wrap('<div class="drag" style="left:20px;"/>'); 
    }); 

問題は、新しく作成されたdivsが既存の設定を継承していることです。

私はそれはそれで動作します別々のコードを追加した場合:

$('.drag').live("drag",function(ev, dd){ 
     $(this).css({ 
      top: Math.round(dd.offsetY/20) * 20, 
      left: Math.round(dd.offsetX/20) * 20 
     }); 
}); 

をしかし、私は、新しく作成されたブロックは、最初のスクリプトを使用します。だから私は問題は、設定が継承されていないと思います

アイデア? ありがとう

答えて

0

新しく作成した要素にスクリプトを追加する必要があります。適用されない場合もあります。ドラッグスクリプトの初期化を別の関数に入れ、新しいdiv要素で呼び出す:

$('#add').click(function(){ 
     var newDiv = $('<div class="handle SE"><div class="drag" style="left:20px;"/>') 
      .text(num++) 
      .appendTo(document.body) 
      .wrap('<div class="drag" style="left:20px;"/>'); 
      initDrag(newDiv); 
    }); 
関連する問題