2015-03-19 42 views
1

我想從javascript生成div並使其可拖動。它正在工作,但是div只能拖動一次。我希望它不斷拖動。jQuery可拖動div只有一次

我知道這是因爲draggable屬性在函數ad_annotation內,但我不知道我該怎麼做。這裏是我的代碼:

 <div id="controle_panel"> 
      <button id="add_annotation" class="btn btn-default" onclick="add_annotation()"> 
       <span class="glyphicon glyphicon-plus"></span> New annotation 
      </button> 
     </div> 
     <div class="video_commands"> 
      <div id="video-wrapper" class="video-wrapper"> 
       <video id="advertisment_video" margin-top="100px" class="video-js 
         vjs-default-skin" preload="auto" data-setup="{}" controls /> 
       <source src=<?php echo '"' . $video["video_link"] . '"'; ?> type="video/mp4"></source> 
      </div> 
      <div id="annotation_confirmation" style="display: none;"> 
       <button id="confirm_annotation" class="btn btn-default" onclick=""> 
        <span class="glyphicon glyphicon-ok"></span> Confirm time and position 
       </button> 
      </div> 
     </div> 
    </div> 
</body> 

<script> 
    function add_annotation() { 
     var v = document.getElementsByTagName('video')[0]; 
     if (v.paused) { 
      alert("Please start the video to place an annotation at the current time"); 
     } else { 
      v.pause(); 
      var retVal = prompt("Enter the text of your anotation", "new anotation"); 
      if (retVal != "new annotation") { 
       var e = $('<div style="background: rgba(255,255,255,0.5); width: 25%;">' + retVal + '</div>'); 
       $('.video-wrapper').prepend(e);  
       e.attr('id', 'annotation'); 
       e.draggable({ 
        containment: '#video-wrapper', 
        cursor: 'move', 
        snap: '#video-wrapper' 
       }); 
       document.getElementById('annotation_confirmation').style.display = "inline"; 
      } 
     } 
    }; 
</script> 
+0

'margin-top =「100px」'它真的有用嗎? – tutankhamun 2015-03-19 07:22:42

回答

2

我會建議在文檔中有可拖動的容器,只是顯示和更新,因爲你需要它而不是創建一個新的。

<div id="dragContainer" style="background: rgba(255,255,255,0.5); width: 25%; display:none"></div> 

然後,在JavaScript你可以把它拖動負載

$(function() { 
    $("#dragContainer").draggable({ 
       containment: '#video-wrapper', 
       cursor: 'move', 
       snap: '#video-wrapper' 
      }); 
}); 

和修改功能:

function add_annotation(){ 
    var v = document.getElementsByTagName('video')[0] 
    if (v.paused){ 
     alert("Please start the video to place an annotation at the current time"); 
    }else{ 
     v.pause(); 
     var retVal = prompt("Enter the text of your anotation", "new anotation"); 
     if (retVal != "new annotation"){ 

      $('#dragContainer').html(retVal).show(); 

      document.getElementById('annotation_confirmation').style.display ="inline";   
     } 
    } 
}; 

然後你只需要在某些時候你的時候觸發隱藏想要擺脫可拖動的容器

+0

謝謝你,但我必須能夠產生。正如你可以在我的代碼中看到的,我有一個生成代碼的按鈕,允許用戶根據需要生成儘可能多的代碼,這是頁面功能的一部分。在此之後,我打算保存創建的div的x和y並將其發送到數據庫。 – 2015-03-19 08:16:18

+0

好的,也許你應該在創建後將創建的div添加到body中,然後 – 2015-03-19 08:26:17

+0

我認爲這是我在這一行上做的:$('。video-wrapper')。prepend(e); – 2015-03-19 10:33:12