JavaScript实现鼠标拖拽元素移动
title: JavaScript实现鼠标拖拽元素移动
id: 1764ed9f-a072-47be-89a0-671d1448b3ce
date: 2023-04-09 16:53:36
auther: admin
cover:
excerpt: JavaScript实现鼠标拖拽元素移动 代码示例如下: Document #wrap { width
permalink: /archives/1681030418027
categories:
- blogs
tags: - JavaScript
- html
JavaScript实现鼠标拖拽元素移动
代码示例如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#wrap {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 100px;
top: 100px;
z-index: 100;
}
</style>
</head>
<body>
<div id="wrap"></div>
</body>
<script>
//鼠标拖拽移动
//1.为div绑定鼠标事件
//2.将鼠标坐标点与div定位位置进行关联
wrap.onmousedown = function (e) {
console.log(e);
var e = e || window.event;
//获取按下的位置
var w = e.clientX;
var h = e.clientY;
console.log('获取按下的位置', 'clientX', w, 'clientY', h);
//获得是鼠标按下时相对于元素的位置
var ex = w - wrap.offsetLeft;
var ey = h - wrap.offsetTop;
document.onmousemove = function (h) {
var h = h || window.event;
var w1 = h.clientX;
var h1 = h.clientY;
console.log('onmousemove', 'w1', w1, 'h1', h1);
wrap.style.left = (w1 - ex) + "px";
wrap.style.top = (h1 - ey) + "px";
}
}
wrap.onmouseup = function () {
document.onmousemove = null;
}
</script>
</html>
运行结果:
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
小森森博客!
喜欢就支持一下吧
打赏
微信
支付宝