1. 程式人生 > >js 實現簡單的拖拽

js 實現簡單的拖拽

offsetx spl pac get 正在 ner .get asc 拖動

步驟

使用 JavaScript 實現拖拽的步驟:

  • 讓元素捕獲事件(mousedown, mousemove & mouseup)
  • 單擊並不釋放,觸發 mousedown,標記開始拖拽,並獲取元素和鼠標的位置
  • 拖動鼠標,觸發 mousemove,不斷的獲取鼠標的位置,並通過計算重新確定元素的位置
  • 釋放師表,觸發 mouseup,結束拖拽,確定元素位置並更新

代碼1:

demo1.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#block {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
}
</style>
</head>
<body>
<div id="block"></div>
<script>
/**
* 拖動元素
* @param elementId 元素id
*/
function drag(elementId) {
var element = document.getElementById(elementId);
var position = {
offsetX: 0, //點擊處偏移元素的X
offsetY: 0, //偏移Y值
state: 0 //是否正處於拖拽狀態,1表示正在拖拽,0表示釋放
};
//獲得兼容的event對象
function getEvent(event) {
return event || window.event;
}
//元素被鼠標拖住
element.addEventListener(‘mousedown‘, function (event) {
//獲得偏移的位置以及更改狀態
var e = getEvent(event);
position.offsetX = e.offsetX;
position.offsetY = e.offsetY;
position.state = 1;
}, false);
//元素移動過程中
document.addEventListener(‘mousemove‘, function (event) {
var e = getEvent(event);
if (position.state) {
position.endX = e.clientX;
position.endY = e.clientY;
//設置絕對位置在文檔中,鼠標當前位置-開始拖拽時的偏移位置
element.style.position = ‘absolute‘;
element.style.top = position.endY - position.offsetY + ‘px‘;
element.style.left = position.endX - position.offsetX + ‘px‘;
}
}, false);
//釋放拖拽狀態
element.addEventListener(‘mouseup‘, function (event) {
position.state = 0;
}, false);
}
drag(‘block‘);
</script>
</body>
</html>

demo2.html <!DOCTYPE html>
<html lang="en">
<body>
<div id="box" class="box" style="width: 100px;height: 100px; position: absolute;background: red;cursor: move;"></div>
<script>
(function () {
var dragging = false;
var boxX, boxY, mouseX, mouseY, offsetX, offsetY; var box = document.getElementById(‘box‘); box.onmousedown = down;
document.onmousemove = move;
document.onmouseup = up; function down(e) {
dragging = true;
boxX = box.offsetLeft;
boxY = box.offsetTop;
mouseX = parseInt(getMouseXY(e).x);
mouseY = parseInt(getMouseXY(e).y);
offsetX = mouseX - boxX;
offsetY = mouseY - boxY;
} function move(e) {
if (dragging) {
var x = getMouseXY(e).x - offsetX;
var y = getMouseXY(e).y - offsetY;
var width = document.documentElement.clientWidth - box.offsetWidth;
var height = document.documentElement.clientHeight - box.offsetHeight; x = Math.min(Math.max(0, x), width);
y = Math.min(Math.max(0, y), height); box.style.left = x + ‘px‘;
box.style.top = y + ‘px‘;
}
} function up(e) {
dragging = false;
} function getMouseXY(e) {
var x = 0, y = 0;
e = e || window.event;
if (e.pageX) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft - document.body.clientLeft;
y = e.clientY + document.body.scrollTop - document.body.clientTop;
}
return {
x: x,
y: y
};
}
})()
</script>
</body>
</html>

js 實現簡單的拖拽