JavaScript拖拽功能

136 阅读1分钟
  • h5新增属性draggable
<div draggable="true"></div>

拖动时:开始 dragstart 进行中 drag 结束 dragend 进入区域:进入时 dragenter 进入后 dragover 离开 dragleave 放置 drop

<body>
    <section class="show">
        <h1>拖动你喜欢的图案到衣服上吧</h1>
        <div class="tshirt">
            <img src="tshirt.png" alt="tshirt">
            <div class="empty"></div>
        </div>
    </section>
    <section>
        <img src="cloth1.png" alt="cloth1">
        <img src="cloth2.png" alt="cloth2">
        <img src="cloth3.png" alt="cloth3">
        <img src="cloth4.png" alt="cloth4">
        <img src="cloth5.png" alt="cloth5">
        <img src="cloth6.png" alt="cloth6">
    </section>
</body>
<script>
    const empty = document.querySelector('div.empty')
    const h1 = document.querySelector('h1')
    let name
    
    document.addEventListener('dragstart', e => {
        name = e.alt
    },false)
    document.addEventListener('drag', e => {
        e.target.style.border = '5px dashed red'
        empty.style.border = '5px dashed red'
    },false)
    document.addEventListener('dragend', e => {
        e.target.style.border = 'none'
        empty.style.border = 'none'
        h1.innerHtml = '拖动你喜欢的图案到衣服上吧'
        h1.style.color = "black"
    })
    empty.addEventListener('dragenter', e => {
        if(empty.firstChild) {
            empty.removeChild(empty.firstChild)
        }
        h1.innerHtml = name
        h1.style.color = "red"
    })
    document.addEventListener('drop', e => {
       e.prenentDefault()
       e.target.appendChild(document.querySelect(`img[alt=${name}]`))
    }, false)
</script>
//一般drop和dragover需要取消默认行为
  • 鼠标事件 鼠标按下 mousedown 鼠标移动 mousemove 鼠标松开 mouseup
<div class="photos">
    <img src="pudding.jpg" alt="" />
    <img src="eye.jpg" alt="eye" />
</div>
<script>
    const h1 = document.querySelect('h1')
    const photos = document.querySelect('div.photos')
    const eye = document.querySelect("img[alt='eye']")
    const photoLeft = photos.offsetLeft
    const photoTop = photos.offsetTop
    eye.addEventListener('mousedown', (e) => {
        const eyeLeft = e.pageX - photoLeft - eye.offsetLeft
        const eyeTop = e.pageY - photoTop - eye.offsetTop
        function moving (e) {
            eye.left = e.pageX - eyeLeft - photoLeft + 'px'
            eye.top = e.pageY - eyeTop - photoTop + 'px'
        }
        document.addEventListener('mousemove', moving, false)
        document.addEventListener('mouseup', (e) => {
            document.removeEventListener('mousemove', moving)
        }, false)
    })
</script>