2011-10-27 52 views
3

我有一個空的div,並且我有另一個可拖動的div。使用jquery添加和刪除div點擊使用

現在,無論我點擊容器,可拖動div應該追加到(0,0)位置,當點擊關閉按鈕時,我需要刪除該可拖動div。我該怎麼做?

這是我有:

http://jsfiddle.net/g6cdL/32/

這裏是我的代碼:

<div id="content" style="background-color: #E5E5E5; width:500px; height:500px;"> 
<div class="demo" style="border-style: dashed; background-color: #CCCCCC"> 

腳本:

<script type="text/javascript"> 
$(function() { 

      $('.demo').draggable({ 

       containment: '#content', 
       cursor: 'move', 
       snap: '#content', 
       stop: function() { 
        var offset = $(this).offset(); 
        var xPos = offset.left; 
        var yPos = offset.top; 
        $('#posX').text('X: ' + xPos); 
        $('#posY').text('Y: ' + yPos); 
       } 
      }) 
    .resizable(); 

}); 
</script> 

CSS:

.demo { 
    position: relative; 
    height: 200px; 
    width: 200px; 
    border: 1px solid #000; 
} 
.demo:before { 
    content: ''; 
    position: absolute; 
    height: 30px; 
     width: 30px; 
     top: -16px; 
     left: -16px; 
    background: url(http://dummyimage.com/30x30/000/fff&text=close); 
    border: 1px solid #000; 
} 

.container 
{ 
    background-color: #E5E5E5; 
    width:500px; 
    height:500px; 
} 
+0

我不認爲這是可以註冊點擊「關閉」按鈕,因爲您使用CSS而不是DOM創建它。做這個,而不是:http://jsfiddle.net/mblase75/g6cdL/42/ – Blazemonger

+0

其實有良好的jquery immage註釋插件,所以我想類似於這個http://www.flipbit.co.uk/jquery-image-annotation .html – coder

回答

1

你的HTML改爲:

<div id="content" style="background-color: #E5E5E5; width:500px; height:500px;"> 
    <div class="demo" style="border-style: dashed; background-color: #CCCCCC"> 
     <div class="closebtn"></div> 
    </div> 
</div> 

然後在你的CSS改變.demo:before.closebtn,並添加到您的JavaScript:

$('.closebtn').click(function(e) { 
    e.stopPropagation(); 
    $(this).parent().hide(); 
}); 
$('#content').click(function(e) { 
    $('.demo').css({top:0,left:0}).show(); 
}); 

http://jsfiddle.net/mblase75/g6cdL/48/

+0

這是行不通的。在每次點擊時,它都會添加一個「.demo」div。我的意思是拖動div並再次點擊內容它再次添加它。 –