[點晴永久免費OA]JS點擊鼠標拖動DIV上下左右移動
當前位置:點晴教程→點晴OA辦公管理信息系統
→『 經驗分享&問題答疑 』
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
position: relative;
border:1px solid red;
width:200px;
height:200px;
}
</style>
</head>
<body>
<div id="dv">ddddddd</div>
<script>
//獲取元素
var dv = document.getElementById('dv');
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
//鼠標按下事件
dv.onmousedown = function(e) {
//獲取x坐標和y坐標
x = e.clientX;
y = e.clientY;
//獲取左部和頂部的偏移量
l = dv.offsetLeft;
t = dv.offsetTop;
//開關打開
isDown = true;
//設置樣式
dv.style.cursor = 'move';
}
//鼠標移動
window.onmousemove = function(e) {
if (isDown == false) {
return;
}
//獲取x和y
var nx = e.clientX;
var ny = e.clientY;
//計算移動后的左偏移量和頂部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
dv.style.left = nl + 'px';
dv.style.top = nt + 'px';
}
//鼠標抬起事件
dv.onmouseup = function() {
//開關關閉
isDown = false;
dv.style.cursor = 'default';
}
</script>
</body>
</html> 該文章在 2022/8/22 15:02:27 編輯過 |
關鍵字查詢
相關文章
正在查詢... |