开发者

How to use HTML5 ondrag event to change the element's position?

For example :

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

(p.s: you should have开发者_如何转开发 jquery and the css file of the page.:-))

Like this page,you can use the jquery extension to change the element's postion.

But html5 and ie offers us the drags api.Like ondrag ondragend and so on.

When I use the new events I can't get the mouse's position on the page,so that I can't achieve the effect like the jquery extension.

ok,how can i use the drags api to achieve that effect?

Thank you.


Highly recommend reading '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>

Further Reading

HTML Drag and Drop API

Native HTML5 Drag and Drop

Native Drag and Drop

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜