【问题标题】:How to use HTML5 ondrag event to change the element's position?如何使用 HTML5 ondrag 事件改变元素的位置?
【发布时间】:2011-11-26 04:57:54
【问题描述】:

例如:

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

(p.s: 你应该有 jquery 和页面的 css 文件。:-))

喜欢这个页面,你可以使用jquery扩展来改变元素的位置。

但是html5和ie为我们提供了drags api。比如ondrag ondragend等等。

当我使用新事件时,无法获取鼠标在页面上的位置,无法达到jquery扩展的效果。

好的,我如何使用 drags api 来实现该效果?

谢谢。

【问题讨论】:

  • 我并没有真正研究过这个,但我想知道你是否可以在 ondragstart 中绑定一个事件并在 ondragend 中取消它。

标签: jquery html drag-and-drop frontend


【解决方案1】:

强烈推荐阅读'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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2011-06-24
    相关资源
    最近更新 更多