javascript - 无法拖动动态附加的 DIV

标签 javascript jquery html drag

http://liveweave.com/rh0ILM

http://jsbin.com/IZodOSU/1/edit

所有具有拖动类的 div 都应该是可拖动的,但是当附加一个 div 时,它就不可拖动了。谁能帮我解决这个问题吗?

HTML

<script src="http://threedubmedia.com/inc/js/jquery-1.7.2.js"></script>
<script src="http://threedubmedia.com/inc/js/jquery.event.drag-2.2.js"></script>
<script src="http://threedubmedia.com/inc/js/jquery.event.drag.live-2.2.js"></script>

<button id="divgen">Gen Div</button>

<div class="container">
    <div class="drag" style="left:20px;"></div>
    <div class="drag" style="left:100px;"></div>
    <div class="drag" style="left:180px;"></div>
</div>

CSS

.drag {
    position: absolute;
    border: 1px solid #89B;
    background: #BCE;
    height: 58px;
    width: 58px;
    cursor: move;
    top: 120px;
}

JS/JQuery

jQuery(function($){
    $('.drag').drag(function( ev, dd ){
        $( this ).css({
            top: dd.offsetY,
            left: dd.offsetX
        });
    });

    $("#divgen").click(function() {
        $("div.container").append('<div id="whatever" class="drag">my div</div>');
    });
});

最佳答案

尝试以下操作。由于 DIV 是动态创建的,因此您必须使用委派。

$('.container').on('drag','.drag',(function( ev, dd ){
    $( this ).css({
        top: dd.offsetY,
        left: dd.offsetX
    });
}));

Working Demo

关于javascript - 无法拖动动态附加的 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18545604/

相关文章:

html - 放大浏览器和元素大小

html - 如何使文本与 CSS 相对对齐?

javascript - 如何使用 split 但跳过 html/javascript/php 和其他内部标签?

javascript - Express:为什么不能在router.use中使用req.body.value?

javascript - 粘贴时如何将url自动转换为超链接

JQuery 选择表中 br 和 td 内的文本

javascript - 自动计算输入字段

javascript - 动态脚本加载第一次有效,但此后无效

JavaScript : Why does my password field not updating at all?

javascript - 将 MySQL 存储过程与 Javascript 对象结合使用