2011-09-27 47 views
3

例如:如何使用HTML5 ondrag事件更改元素的位置?

https://github.com/lbj96347/easypost/blob/master/test.html

(PS:你應該有jQuery和頁面的CSS文件:-))

喜歡這個頁面,你可以使用jQuery的擴展名更改元素的位置。

但是html5和ie爲我們提供了drags api.Like ondrag ondragend等。

當我使用新的事件時,我無法獲得鼠標在頁面上的位置,所以我無法達到像jQuery擴展那樣的效果。

好的,我如何使用drags api來實現這種效果?

謝謝。

+0

我真的不研究這個,但我不知道,如果你能在綁定和ondragstart解除綁定事件它在漸進。 –

回答

0

強烈推薦閱讀'The HTML5 drag and drop disaster'

<!DOCTYPE html> 
<html> 
    <head> 
     <style> 
      html { 
       height: 100%; 
      } 

      body { 
       margin: 0; 
       padding: 0; 
       height: 100%; 
      } 

      section { 
       height: 100%; 
      } 

      div { 
       width: 40px; 
       height: 40px; 
       position: absolute; 
       background-color: #000; 
      } 
     </style> 
    </head> 
    <body> 
     <section ondragenter="return drag_enter(event)" ondrop="return drag_drop(event)" ondragover="return drag_over(event)"> 
      <div id="item" draggable="true" ondragstart="return drag_start(event)"></div> 
     </section> 
     <script> 
      function drag_enter(action) 
      { 
      action.preventDefault(); 

      return true; 
      } 

      function drag_over(action) 
      { 
       action.preventDefault(); 
      } 

      function drag_start(action) 
      { 
       action.dataTransfer.effectAllowed = 'move'; 
       action.dataTransfer.setData('id', action.target.getAttribute('id')); 

       return true; 
      } 

      function drag_drop(action) 
      { 
       var id = action.dataTransfer.getData('id'); 

       var element = document.getElementById(id); 
       element.style.top = action.clientY + 'px'; 
       element.style.left = action.clientX + 'px'; 

       if (action.stopPropagation) 
       { 
        action.stopPropagation(); 
       } 

       return false; 
      } 
     </script> 
    </body> 
</html> 

進一步閱讀

HTML Drag and Drop API

Native HTML5 Drag and Drop

Native Drag and Drop