Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thực thi script khi phần tử đã được kéo đến mục thả hợp lệ trong HTML?

Khi một phần tử đã được kéo trong HTML đến mục thả hợp lệ, thuộc tính ondragenter kích hoạt.

Ví dụ

Bạn có thể chạy mã sau để triển khai thuộc tính ondragenter:

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      #boxA, #boxB {
        float:left; padding:10px; margin:10px; -moz-user-select:none;
      }
      #boxA { background-color: #6633FF; width:75px; height:75px; }
      #boxB { background-color: #FF6699; width:150px; height:150px; }
    </style>
    <script type="text/javascript">
      function dragStart(ev) {
        ev.dataTransfer.effectAllowed = 'move';
        ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
        ev.dataTransfer.setDragImage(ev.target,0,0);
        return true;
      }
    </script>
  </head>
  <body>
    <center>
      <h2>Demo kéo thả HTML5</h2>
      <div>Kéo hộp tím xem.</div>
      <div id="boxA" draggable="true" ondragstart="return dragStart(ev)">
        <p>Kéo tôi</p>
      </div>
      <div id="boxB">Thùng rác</div>
    </center>
  </body>
</html>