使用Drag随意拖拽图片到页面的任意处,并兼容移动端


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,
    maximum-scale=1, user-scalable=no">
    <link rel="icon" href="https://xlzy520.cn/icons/lo.ico">
    <title>跳舞小萝莉随意drag到任意处title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
        }

        #dance {
            cursor: pointer;
        }
    style>
head>
<body ondrop="drop(event)" ondragover="allowDrop(event)" ontouchmove="drop(event)">
<div class="main">
    <img style="position: absolute;left: 0;top: 0;"
    src="https://xlzy520.cn/images/2.gif" 
    draggable="true" id="dance"
    ondragstart="drag(event)" ontouchstart="drag(event)">
div>
<script>
  (function () {
    document.getElementsByTagName('body')[0].style.height = window.innerHeight + 'px'
    document.getElementsByTagName('body')[0].style.width = window.innerWidth + 'px'
  })()
  let dance = document.getElementById('dance')
  let dragOffset={
    X1:null,
    Y1:null
  }

  function drag(e) {
    if (e.type === 'dragstart') {  //根据e.type判断是PC端还是移动端
      e = event ? event : e
    }else {
      if (event.touches) {
        e = event.touches[0] ? event.touches[0]:event;
      }
    }
    dragOffset.X1 = e.clientX - parseInt(dance.style.left)
    dragOffset.Y1 = e.clientY - parseInt(dance.style.top)
    // 鼠标点击的位置在整个页面上的坐标是(e.clientX,e.clientY)
    // 鼠标点击的位置在图片的位置坐标为(X1,Y1)
  }

  function drop(e) {
    if (e.type === 'drop'){
      e = event ? event : e
      e.preventDefault()
    } else {
      if (event.touches) {
        e = event.touches[0] ? event.touches[0]:event;
      }
    }
    dance.style.left = e.clientX - dragOffset.X1 + 'px'
    dance.style.top = e.clientY - dragOffset.Y1 + 'px'
    // 根据鼠标点击的位置在整个页面上的坐标和在图片上的坐标来确定整个图片的坐标
  }


  function allowDrop(e) {
    e = event ? event : e
    // 移动过程中触发
  }

  document.ondragover = function () {
    //取消事件的默认行为
    return false;
  }
  document.ondrop = function () {
    //取消事件的默认行为
    return false
  }
script>

body>
html>

你可能感兴趣的:(JavaScript,html5)