2011-12-24 3 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의 호르하게이 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;"/>'); 
    }); 

그리고 내가 가진 문제는 새로 생성 된 div가 이미 기존 설정을 상속한다는 점입니다.

나는 그와 함께 작동합니다 별도의 코드를 추가하는 경우 :

$('.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); 
    }); 
관련 문제