[點(diǎn)晴永久免費(fèi)OA]JS點(diǎn)擊鼠標(biāo)拖動DIV上下左右移動
<!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;
//鼠標(biāo)按下事件
dv.onmousedown = function(e) {
//獲取x坐標(biāo)和y坐標(biāo)
x = e.clientX;
y = e.clientY;
//獲取左部和頂部的偏移量
l = dv.offsetLeft;
t = dv.offsetTop;
//開關(guān)打開
isDown = true;
//設(shè)置樣式
dv.style.cursor = 'move';
}
//鼠標(biāo)移動
window.onmousemove = function(e) {
if (isDown == false) {
return;
}
//獲取x和y
var nx = e.clientX;
var ny = e.clientY;
//計(jì)算移動后的左偏移量和頂部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
dv.style.left = nl + 'px';
dv.style.top = nt + 'px';
}
//鼠標(biāo)抬起事件
dv.onmouseup = function() {
//開關(guān)關(guān)閉
isDown = false;
dv.style.cursor = 'default';
}
</script>
</body>
</html> 該文章在 2022/8/22 15:02:27 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |