JavaScript拖拽

Posted znj211985

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript拖拽相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS拖拽</title>
<style>
*{padding: 0; margin: 0; }
.box{width: 100px;height: 100px;background: blue;position: absolute; }
</style>
<script src="jquery.min.js"></script>
<script>
var isDown = false;
var ObjLeft, ObjTop, posX, posY, obj,offsetX,offsetY;
$(function(){
obj=$("#box");
obj.onmousedown = down;
document.onmousemove = move;
document.onmouseup = up;
})
function down(event){
isDown=true;
obj.style.cursor = "move";
ObjLeft = obj.offset().left;
ObjTop = obj.offset().top;
}
</script>
<script>
var isDown = false;
var ObjLeft, ObjTop, posX, posY, obj,offsetX,offsetY;
window.onload = function() {
obj = document.getElementById(‘box‘);
obj.onmousedown = down;
document.onmousemove = move;
document.onmouseup = up;
}
function down(event) {
obj.style.cursor = "move";
isDown = true;
ObjLeft = obj.offsetLeft;
ObjTop = obj.offsetTop;
posX = parseInt(mousePosition(event).x);
posY = parseInt(mousePosition(event).y);
offsetX=posX-ObjLeft;
offsetY=posY-ObjTop;
}
function move(event) {
if (isDown == true) {
var x=mousePosition(event).x-offsetX;
var y=mousePosition(event).y-offsetY;
var w = document.documentElement.clientWidth - obj.offsetWidth;
var h = document.documentElement.clientHeight - obj.offsetHeight;
console.log(x + ‘,‘ + y);
x=Math.min(w,Math.max(0,x));
y=Math.min(h,Math.max(0,y));
obj.style.left = x + ‘px‘;
obj.style.top = y + ‘px‘;
}
}

function up() {
isDown = false;
}

function mousePosition(evt) {
var xPos, yPos;
evt = evt || window.event;
if (evt.pageX) {
xPos = evt.pageX;
yPos = evt.pageY;
} else {
xPos = evt.clientX + document.body.scrollLeft - document.body.clientLeft;
yPos = evt.clientY + document.body.scrollTop - document.body.clientTop;
}
return {
x: xPos,
y: yPos
}
}
</script>
</head>
<body>
<div id="box" class="box"></div>
</body>
</html>

以上是关于JavaScript拖拽的主要内容,如果未能解决你的问题,请参考以下文章

javascript动画系列第一篇——模拟拖拽

JavaScript 拖拽实现

JavaScript 拖拽实现

javascript 拖拽

第一百三十五节,JavaScript,封装库--拖拽

JavaScript鼠标拖拽特效及相关问题总结