如何在jquery中继承新创建的对象的现有设置?

时间:2011-12-24 21:36:26

标签: jquery inheritance draggable

我正在使用jquery插件来创建一些可拖动的对象。

插件为here,演示为here

我对jsfiddle的测试也是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>

然后我使用一个按钮添加更多视频:

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
        });
});

但我希望新创建的块使用第一个脚本。所以我猜问题是设置不是继承的

有什么想法吗? 感谢

1 个答案:

答案 0 :(得分: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);
    });
相关问题