首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

实现一个可以拖拽的div

Sonder
2020-08-08
1135字
3分钟
浏览 (2.1k)

实现一个可以拖拽的DIV

复制代码
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Document</title>
</head>
<style>
   #xxx {
       position: fixed;
       width: 150px;
       height: 150px;
       background: red
   }
</style>
<body>
   <div id="xxx"></div>

   <script type="text/javascript">
var xxx = document.getElementById('xxx')
var dragging = false
var position = null

xxx.addEventListener('mousedown',function(e){
 dragging = true
 position = [e.clientX, e.clientY]
})


document.addEventListener('mousemove', function(e){
 if(dragging === false) return null
 const x = e.clientX
 const y = e.clientY
 const deltaX = x - position[0]
 const deltaY = y - position[1]
 const left = parseInt(xxx.style.left || 0)
 const top = parseInt(xxx.style.top || 0)
 xxx.style.left = left + deltaX + 'px'
 xxx.style.top = top + deltaY + 'px'
 position = [x, y]
})
document.addEventListener('mouseup', function(e){
 dragging = false
})

   </script>
</body>
</html>
下一篇 / Vue路由懒加载以及组件懒加载

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)